17db96d56Sopenharmony_ci:mod:`wsgiref` --- WSGI Utilities and Reference Implementation 27db96d56Sopenharmony_ci============================================================== 37db96d56Sopenharmony_ci 47db96d56Sopenharmony_ci.. module:: wsgiref 57db96d56Sopenharmony_ci :synopsis: WSGI Utilities and Reference Implementation. 67db96d56Sopenharmony_ci 77db96d56Sopenharmony_ci.. moduleauthor:: Phillip J. Eby <pje@telecommunity.com> 87db96d56Sopenharmony_ci.. sectionauthor:: Phillip J. Eby <pje@telecommunity.com> 97db96d56Sopenharmony_ci 107db96d56Sopenharmony_ci**Source code:** :source:`Lib/wsgiref` 117db96d56Sopenharmony_ci 127db96d56Sopenharmony_ci-------------- 137db96d56Sopenharmony_ci 147db96d56Sopenharmony_ciThe Web Server Gateway Interface (WSGI) is a standard interface between web 157db96d56Sopenharmony_ciserver software and web applications written in Python. Having a standard 167db96d56Sopenharmony_ciinterface makes it easy to use an application that supports WSGI with a number 177db96d56Sopenharmony_ciof different web servers. 187db96d56Sopenharmony_ci 197db96d56Sopenharmony_ciOnly authors of web servers and programming frameworks need to know every detail 207db96d56Sopenharmony_ciand corner case of the WSGI design. You don't need to understand every detail 217db96d56Sopenharmony_ciof WSGI just to install a WSGI application or to write a web application using 227db96d56Sopenharmony_cian existing framework. 237db96d56Sopenharmony_ci 247db96d56Sopenharmony_ci:mod:`wsgiref` is a reference implementation of the WSGI specification that can 257db96d56Sopenharmony_cibe used to add WSGI support to a web server or framework. It provides utilities 267db96d56Sopenharmony_cifor manipulating WSGI environment variables and response headers, base classes 277db96d56Sopenharmony_cifor implementing WSGI servers, a demo HTTP server that serves WSGI applications, 287db96d56Sopenharmony_citypes for static type checking, 297db96d56Sopenharmony_ciand a validation tool that checks WSGI servers and applications for conformance 307db96d56Sopenharmony_cito the WSGI specification (:pep:`3333`). 317db96d56Sopenharmony_ci 327db96d56Sopenharmony_ciSee `wsgi.readthedocs.io <https://wsgi.readthedocs.io/>`_ for more information about WSGI, and links 337db96d56Sopenharmony_cito tutorials and other resources. 347db96d56Sopenharmony_ci 357db96d56Sopenharmony_ci.. XXX If you're just trying to write a web application... 367db96d56Sopenharmony_ci 377db96d56Sopenharmony_ci 387db96d56Sopenharmony_ci:mod:`wsgiref.util` -- WSGI environment utilities 397db96d56Sopenharmony_ci------------------------------------------------- 407db96d56Sopenharmony_ci 417db96d56Sopenharmony_ci.. module:: wsgiref.util 427db96d56Sopenharmony_ci :synopsis: WSGI environment utilities. 437db96d56Sopenharmony_ci 447db96d56Sopenharmony_ci 457db96d56Sopenharmony_ciThis module provides a variety of utility functions for working with WSGI 467db96d56Sopenharmony_cienvironments. A WSGI environment is a dictionary containing HTTP request 477db96d56Sopenharmony_civariables as described in :pep:`3333`. All of the functions taking an *environ* 487db96d56Sopenharmony_ciparameter expect a WSGI-compliant dictionary to be supplied; please see 497db96d56Sopenharmony_ci:pep:`3333` for a detailed specification and 507db96d56Sopenharmony_ci:data:`~wsgiref.types.WSGIEnvironment` for a type alias that can be used 517db96d56Sopenharmony_ciin type annotations. 527db96d56Sopenharmony_ci 537db96d56Sopenharmony_ci 547db96d56Sopenharmony_ci.. function:: guess_scheme(environ) 557db96d56Sopenharmony_ci 567db96d56Sopenharmony_ci Return a guess for whether ``wsgi.url_scheme`` should be "http" or "https", by 577db96d56Sopenharmony_ci checking for a ``HTTPS`` environment variable in the *environ* dictionary. The 587db96d56Sopenharmony_ci return value is a string. 597db96d56Sopenharmony_ci 607db96d56Sopenharmony_ci This function is useful when creating a gateway that wraps CGI or a CGI-like 617db96d56Sopenharmony_ci protocol such as FastCGI. Typically, servers providing such protocols will 627db96d56Sopenharmony_ci include a ``HTTPS`` variable with a value of "1", "yes", or "on" when a request 637db96d56Sopenharmony_ci is received via SSL. So, this function returns "https" if such a value is 647db96d56Sopenharmony_ci found, and "http" otherwise. 657db96d56Sopenharmony_ci 667db96d56Sopenharmony_ci 677db96d56Sopenharmony_ci.. function:: request_uri(environ, include_query=True) 687db96d56Sopenharmony_ci 697db96d56Sopenharmony_ci Return the full request URI, optionally including the query string, using the 707db96d56Sopenharmony_ci algorithm found in the "URL Reconstruction" section of :pep:`3333`. If 717db96d56Sopenharmony_ci *include_query* is false, the query string is not included in the resulting URI. 727db96d56Sopenharmony_ci 737db96d56Sopenharmony_ci 747db96d56Sopenharmony_ci.. function:: application_uri(environ) 757db96d56Sopenharmony_ci 767db96d56Sopenharmony_ci Similar to :func:`request_uri`, except that the ``PATH_INFO`` and 777db96d56Sopenharmony_ci ``QUERY_STRING`` variables are ignored. The result is the base URI of the 787db96d56Sopenharmony_ci application object addressed by the request. 797db96d56Sopenharmony_ci 807db96d56Sopenharmony_ci 817db96d56Sopenharmony_ci.. function:: shift_path_info(environ) 827db96d56Sopenharmony_ci 837db96d56Sopenharmony_ci Shift a single name from ``PATH_INFO`` to ``SCRIPT_NAME`` and return the name. 847db96d56Sopenharmony_ci The *environ* dictionary is *modified* in-place; use a copy if you need to keep 857db96d56Sopenharmony_ci the original ``PATH_INFO`` or ``SCRIPT_NAME`` intact. 867db96d56Sopenharmony_ci 877db96d56Sopenharmony_ci If there are no remaining path segments in ``PATH_INFO``, ``None`` is returned. 887db96d56Sopenharmony_ci 897db96d56Sopenharmony_ci Typically, this routine is used to process each portion of a request URI path, 907db96d56Sopenharmony_ci for example to treat the path as a series of dictionary keys. This routine 917db96d56Sopenharmony_ci modifies the passed-in environment to make it suitable for invoking another WSGI 927db96d56Sopenharmony_ci application that is located at the target URI. For example, if there is a WSGI 937db96d56Sopenharmony_ci application at ``/foo``, and the request URI path is ``/foo/bar/baz``, and the 947db96d56Sopenharmony_ci WSGI application at ``/foo`` calls :func:`shift_path_info`, it will receive the 957db96d56Sopenharmony_ci string "bar", and the environment will be updated to be suitable for passing to 967db96d56Sopenharmony_ci a WSGI application at ``/foo/bar``. That is, ``SCRIPT_NAME`` will change from 977db96d56Sopenharmony_ci ``/foo`` to ``/foo/bar``, and ``PATH_INFO`` will change from ``/bar/baz`` to 987db96d56Sopenharmony_ci ``/baz``. 997db96d56Sopenharmony_ci 1007db96d56Sopenharmony_ci When ``PATH_INFO`` is just a "/", this routine returns an empty string and 1017db96d56Sopenharmony_ci appends a trailing slash to ``SCRIPT_NAME``, even though empty path segments are 1027db96d56Sopenharmony_ci normally ignored, and ``SCRIPT_NAME`` doesn't normally end in a slash. This is 1037db96d56Sopenharmony_ci intentional behavior, to ensure that an application can tell the difference 1047db96d56Sopenharmony_ci between URIs ending in ``/x`` from ones ending in ``/x/`` when using this 1057db96d56Sopenharmony_ci routine to do object traversal. 1067db96d56Sopenharmony_ci 1077db96d56Sopenharmony_ci 1087db96d56Sopenharmony_ci.. function:: setup_testing_defaults(environ) 1097db96d56Sopenharmony_ci 1107db96d56Sopenharmony_ci Update *environ* with trivial defaults for testing purposes. 1117db96d56Sopenharmony_ci 1127db96d56Sopenharmony_ci This routine adds various parameters required for WSGI, including ``HTTP_HOST``, 1137db96d56Sopenharmony_ci ``SERVER_NAME``, ``SERVER_PORT``, ``REQUEST_METHOD``, ``SCRIPT_NAME``, 1147db96d56Sopenharmony_ci ``PATH_INFO``, and all of the :pep:`3333`\ -defined ``wsgi.*`` variables. It 1157db96d56Sopenharmony_ci only supplies default values, and does not replace any existing settings for 1167db96d56Sopenharmony_ci these variables. 1177db96d56Sopenharmony_ci 1187db96d56Sopenharmony_ci This routine is intended to make it easier for unit tests of WSGI servers and 1197db96d56Sopenharmony_ci applications to set up dummy environments. It should NOT be used by actual WSGI 1207db96d56Sopenharmony_ci servers or applications, since the data is fake! 1217db96d56Sopenharmony_ci 1227db96d56Sopenharmony_ci Example usage:: 1237db96d56Sopenharmony_ci 1247db96d56Sopenharmony_ci from wsgiref.util import setup_testing_defaults 1257db96d56Sopenharmony_ci from wsgiref.simple_server import make_server 1267db96d56Sopenharmony_ci 1277db96d56Sopenharmony_ci # A relatively simple WSGI application. It's going to print out the 1287db96d56Sopenharmony_ci # environment dictionary after being updated by setup_testing_defaults 1297db96d56Sopenharmony_ci def simple_app(environ, start_response): 1307db96d56Sopenharmony_ci setup_testing_defaults(environ) 1317db96d56Sopenharmony_ci 1327db96d56Sopenharmony_ci status = '200 OK' 1337db96d56Sopenharmony_ci headers = [('Content-type', 'text/plain; charset=utf-8')] 1347db96d56Sopenharmony_ci 1357db96d56Sopenharmony_ci start_response(status, headers) 1367db96d56Sopenharmony_ci 1377db96d56Sopenharmony_ci ret = [("%s: %s\n" % (key, value)).encode("utf-8") 1387db96d56Sopenharmony_ci for key, value in environ.items()] 1397db96d56Sopenharmony_ci return ret 1407db96d56Sopenharmony_ci 1417db96d56Sopenharmony_ci with make_server('', 8000, simple_app) as httpd: 1427db96d56Sopenharmony_ci print("Serving on port 8000...") 1437db96d56Sopenharmony_ci httpd.serve_forever() 1447db96d56Sopenharmony_ci 1457db96d56Sopenharmony_ci 1467db96d56Sopenharmony_ciIn addition to the environment functions above, the :mod:`wsgiref.util` module 1477db96d56Sopenharmony_cialso provides these miscellaneous utilities: 1487db96d56Sopenharmony_ci 1497db96d56Sopenharmony_ci 1507db96d56Sopenharmony_ci.. function:: is_hop_by_hop(header_name) 1517db96d56Sopenharmony_ci 1527db96d56Sopenharmony_ci Return ``True`` if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header, as defined by 1537db96d56Sopenharmony_ci :rfc:`2616`. 1547db96d56Sopenharmony_ci 1557db96d56Sopenharmony_ci 1567db96d56Sopenharmony_ci.. class:: FileWrapper(filelike, blksize=8192) 1577db96d56Sopenharmony_ci 1587db96d56Sopenharmony_ci A concrete implementation of the :class:`wsgiref.types.FileWrapper` 1597db96d56Sopenharmony_ci protocol used to convert a file-like object to an :term:`iterator`. 1607db96d56Sopenharmony_ci The resulting objects 1617db96d56Sopenharmony_ci are :term:`iterable`\ s. As the object is iterated over, the 1627db96d56Sopenharmony_ci optional *blksize* parameter will be repeatedly passed to the *filelike* 1637db96d56Sopenharmony_ci object's :meth:`read` method to obtain bytestrings to yield. When :meth:`read` 1647db96d56Sopenharmony_ci returns an empty bytestring, iteration is ended and is not resumable. 1657db96d56Sopenharmony_ci 1667db96d56Sopenharmony_ci If *filelike* has a :meth:`close` method, the returned object will also have a 1677db96d56Sopenharmony_ci :meth:`close` method, and it will invoke the *filelike* object's :meth:`close` 1687db96d56Sopenharmony_ci method when called. 1697db96d56Sopenharmony_ci 1707db96d56Sopenharmony_ci Example usage:: 1717db96d56Sopenharmony_ci 1727db96d56Sopenharmony_ci from io import StringIO 1737db96d56Sopenharmony_ci from wsgiref.util import FileWrapper 1747db96d56Sopenharmony_ci 1757db96d56Sopenharmony_ci # We're using a StringIO-buffer for as the file-like object 1767db96d56Sopenharmony_ci filelike = StringIO("This is an example file-like object"*10) 1777db96d56Sopenharmony_ci wrapper = FileWrapper(filelike, blksize=5) 1787db96d56Sopenharmony_ci 1797db96d56Sopenharmony_ci for chunk in wrapper: 1807db96d56Sopenharmony_ci print(chunk) 1817db96d56Sopenharmony_ci 1827db96d56Sopenharmony_ci .. versionchanged:: 3.11 1837db96d56Sopenharmony_ci Support for :meth:`__getitem__` method has been removed. 1847db96d56Sopenharmony_ci 1857db96d56Sopenharmony_ci 1867db96d56Sopenharmony_ci:mod:`wsgiref.headers` -- WSGI response header tools 1877db96d56Sopenharmony_ci---------------------------------------------------- 1887db96d56Sopenharmony_ci 1897db96d56Sopenharmony_ci.. module:: wsgiref.headers 1907db96d56Sopenharmony_ci :synopsis: WSGI response header tools. 1917db96d56Sopenharmony_ci 1927db96d56Sopenharmony_ci 1937db96d56Sopenharmony_ciThis module provides a single class, :class:`Headers`, for convenient 1947db96d56Sopenharmony_cimanipulation of WSGI response headers using a mapping-like interface. 1957db96d56Sopenharmony_ci 1967db96d56Sopenharmony_ci 1977db96d56Sopenharmony_ci.. class:: Headers([headers]) 1987db96d56Sopenharmony_ci 1997db96d56Sopenharmony_ci Create a mapping-like object wrapping *headers*, which must be a list of header 2007db96d56Sopenharmony_ci name/value tuples as described in :pep:`3333`. The default value of *headers* is 2017db96d56Sopenharmony_ci an empty list. 2027db96d56Sopenharmony_ci 2037db96d56Sopenharmony_ci :class:`Headers` objects support typical mapping operations including 2047db96d56Sopenharmony_ci :meth:`__getitem__`, :meth:`get`, :meth:`__setitem__`, :meth:`setdefault`, 2057db96d56Sopenharmony_ci :meth:`__delitem__` and :meth:`__contains__`. For each of 2067db96d56Sopenharmony_ci these methods, the key is the header name (treated case-insensitively), and the 2077db96d56Sopenharmony_ci value is the first value associated with that header name. Setting a header 2087db96d56Sopenharmony_ci deletes any existing values for that header, then adds a new value at the end of 2097db96d56Sopenharmony_ci the wrapped header list. Headers' existing order is generally maintained, with 2107db96d56Sopenharmony_ci new headers added to the end of the wrapped list. 2117db96d56Sopenharmony_ci 2127db96d56Sopenharmony_ci Unlike a dictionary, :class:`Headers` objects do not raise an error when you try 2137db96d56Sopenharmony_ci to get or delete a key that isn't in the wrapped header list. Getting a 2147db96d56Sopenharmony_ci nonexistent header just returns ``None``, and deleting a nonexistent header does 2157db96d56Sopenharmony_ci nothing. 2167db96d56Sopenharmony_ci 2177db96d56Sopenharmony_ci :class:`Headers` objects also support :meth:`keys`, :meth:`values`, and 2187db96d56Sopenharmony_ci :meth:`items` methods. The lists returned by :meth:`keys` and :meth:`items` can 2197db96d56Sopenharmony_ci include the same key more than once if there is a multi-valued header. The 2207db96d56Sopenharmony_ci ``len()`` of a :class:`Headers` object is the same as the length of its 2217db96d56Sopenharmony_ci :meth:`items`, which is the same as the length of the wrapped header list. In 2227db96d56Sopenharmony_ci fact, the :meth:`items` method just returns a copy of the wrapped header list. 2237db96d56Sopenharmony_ci 2247db96d56Sopenharmony_ci Calling ``bytes()`` on a :class:`Headers` object returns a formatted bytestring 2257db96d56Sopenharmony_ci suitable for transmission as HTTP response headers. Each header is placed on a 2267db96d56Sopenharmony_ci line with its value, separated by a colon and a space. Each line is terminated 2277db96d56Sopenharmony_ci by a carriage return and line feed, and the bytestring is terminated with a 2287db96d56Sopenharmony_ci blank line. 2297db96d56Sopenharmony_ci 2307db96d56Sopenharmony_ci In addition to their mapping interface and formatting features, :class:`Headers` 2317db96d56Sopenharmony_ci objects also have the following methods for querying and adding multi-valued 2327db96d56Sopenharmony_ci headers, and for adding headers with MIME parameters: 2337db96d56Sopenharmony_ci 2347db96d56Sopenharmony_ci 2357db96d56Sopenharmony_ci .. method:: Headers.get_all(name) 2367db96d56Sopenharmony_ci 2377db96d56Sopenharmony_ci Return a list of all the values for the named header. 2387db96d56Sopenharmony_ci 2397db96d56Sopenharmony_ci The returned list will be sorted in the order they appeared in the original 2407db96d56Sopenharmony_ci header list or were added to this instance, and may contain duplicates. Any 2417db96d56Sopenharmony_ci fields deleted and re-inserted are always appended to the header list. If no 2427db96d56Sopenharmony_ci fields exist with the given name, returns an empty list. 2437db96d56Sopenharmony_ci 2447db96d56Sopenharmony_ci 2457db96d56Sopenharmony_ci .. method:: Headers.add_header(name, value, **_params) 2467db96d56Sopenharmony_ci 2477db96d56Sopenharmony_ci Add a (possibly multi-valued) header, with optional MIME parameters specified 2487db96d56Sopenharmony_ci via keyword arguments. 2497db96d56Sopenharmony_ci 2507db96d56Sopenharmony_ci *name* is the header field to add. Keyword arguments can be used to set MIME 2517db96d56Sopenharmony_ci parameters for the header field. Each parameter must be a string or ``None``. 2527db96d56Sopenharmony_ci Underscores in parameter names are converted to dashes, since dashes are illegal 2537db96d56Sopenharmony_ci in Python identifiers, but many MIME parameter names include dashes. If the 2547db96d56Sopenharmony_ci parameter value is a string, it is added to the header value parameters in the 2557db96d56Sopenharmony_ci form ``name="value"``. If it is ``None``, only the parameter name is added. 2567db96d56Sopenharmony_ci (This is used for MIME parameters without a value.) Example usage:: 2577db96d56Sopenharmony_ci 2587db96d56Sopenharmony_ci h.add_header('content-disposition', 'attachment', filename='bud.gif') 2597db96d56Sopenharmony_ci 2607db96d56Sopenharmony_ci The above will add a header that looks like this:: 2617db96d56Sopenharmony_ci 2627db96d56Sopenharmony_ci Content-Disposition: attachment; filename="bud.gif" 2637db96d56Sopenharmony_ci 2647db96d56Sopenharmony_ci 2657db96d56Sopenharmony_ci .. versionchanged:: 3.5 2667db96d56Sopenharmony_ci *headers* parameter is optional. 2677db96d56Sopenharmony_ci 2687db96d56Sopenharmony_ci 2697db96d56Sopenharmony_ci:mod:`wsgiref.simple_server` -- a simple WSGI HTTP server 2707db96d56Sopenharmony_ci--------------------------------------------------------- 2717db96d56Sopenharmony_ci 2727db96d56Sopenharmony_ci.. module:: wsgiref.simple_server 2737db96d56Sopenharmony_ci :synopsis: A simple WSGI HTTP server. 2747db96d56Sopenharmony_ci 2757db96d56Sopenharmony_ci 2767db96d56Sopenharmony_ciThis module implements a simple HTTP server (based on :mod:`http.server`) 2777db96d56Sopenharmony_cithat serves WSGI applications. Each server instance serves a single WSGI 2787db96d56Sopenharmony_ciapplication on a given host and port. If you want to serve multiple 2797db96d56Sopenharmony_ciapplications on a single host and port, you should create a WSGI application 2807db96d56Sopenharmony_cithat parses ``PATH_INFO`` to select which application to invoke for each 2817db96d56Sopenharmony_cirequest. (E.g., using the :func:`shift_path_info` function from 2827db96d56Sopenharmony_ci:mod:`wsgiref.util`.) 2837db96d56Sopenharmony_ci 2847db96d56Sopenharmony_ci 2857db96d56Sopenharmony_ci.. function:: make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler) 2867db96d56Sopenharmony_ci 2877db96d56Sopenharmony_ci Create a new WSGI server listening on *host* and *port*, accepting connections 2887db96d56Sopenharmony_ci for *app*. The return value is an instance of the supplied *server_class*, and 2897db96d56Sopenharmony_ci will process requests using the specified *handler_class*. *app* must be a WSGI 2907db96d56Sopenharmony_ci application object, as defined by :pep:`3333`. 2917db96d56Sopenharmony_ci 2927db96d56Sopenharmony_ci Example usage:: 2937db96d56Sopenharmony_ci 2947db96d56Sopenharmony_ci from wsgiref.simple_server import make_server, demo_app 2957db96d56Sopenharmony_ci 2967db96d56Sopenharmony_ci with make_server('', 8000, demo_app) as httpd: 2977db96d56Sopenharmony_ci print("Serving HTTP on port 8000...") 2987db96d56Sopenharmony_ci 2997db96d56Sopenharmony_ci # Respond to requests until process is killed 3007db96d56Sopenharmony_ci httpd.serve_forever() 3017db96d56Sopenharmony_ci 3027db96d56Sopenharmony_ci # Alternative: serve one request, then exit 3037db96d56Sopenharmony_ci httpd.handle_request() 3047db96d56Sopenharmony_ci 3057db96d56Sopenharmony_ci 3067db96d56Sopenharmony_ci.. function:: demo_app(environ, start_response) 3077db96d56Sopenharmony_ci 3087db96d56Sopenharmony_ci This function is a small but complete WSGI application that returns a text page 3097db96d56Sopenharmony_ci containing the message "Hello world!" and a list of the key/value pairs provided 3107db96d56Sopenharmony_ci in the *environ* parameter. It's useful for verifying that a WSGI server (such 3117db96d56Sopenharmony_ci as :mod:`wsgiref.simple_server`) is able to run a simple WSGI application 3127db96d56Sopenharmony_ci correctly. 3137db96d56Sopenharmony_ci 3147db96d56Sopenharmony_ci 3157db96d56Sopenharmony_ci.. class:: WSGIServer(server_address, RequestHandlerClass) 3167db96d56Sopenharmony_ci 3177db96d56Sopenharmony_ci Create a :class:`WSGIServer` instance. *server_address* should be a 3187db96d56Sopenharmony_ci ``(host,port)`` tuple, and *RequestHandlerClass* should be the subclass of 3197db96d56Sopenharmony_ci :class:`http.server.BaseHTTPRequestHandler` that will be used to process 3207db96d56Sopenharmony_ci requests. 3217db96d56Sopenharmony_ci 3227db96d56Sopenharmony_ci You do not normally need to call this constructor, as the :func:`make_server` 3237db96d56Sopenharmony_ci function can handle all the details for you. 3247db96d56Sopenharmony_ci 3257db96d56Sopenharmony_ci :class:`WSGIServer` is a subclass of :class:`http.server.HTTPServer`, so all 3267db96d56Sopenharmony_ci of its methods (such as :meth:`serve_forever` and :meth:`handle_request`) are 3277db96d56Sopenharmony_ci available. :class:`WSGIServer` also provides these WSGI-specific methods: 3287db96d56Sopenharmony_ci 3297db96d56Sopenharmony_ci 3307db96d56Sopenharmony_ci .. method:: WSGIServer.set_app(application) 3317db96d56Sopenharmony_ci 3327db96d56Sopenharmony_ci Sets the callable *application* as the WSGI application that will receive 3337db96d56Sopenharmony_ci requests. 3347db96d56Sopenharmony_ci 3357db96d56Sopenharmony_ci 3367db96d56Sopenharmony_ci .. method:: WSGIServer.get_app() 3377db96d56Sopenharmony_ci 3387db96d56Sopenharmony_ci Returns the currently set application callable. 3397db96d56Sopenharmony_ci 3407db96d56Sopenharmony_ci Normally, however, you do not need to use these additional methods, as 3417db96d56Sopenharmony_ci :meth:`set_app` is normally called by :func:`make_server`, and the 3427db96d56Sopenharmony_ci :meth:`get_app` exists mainly for the benefit of request handler instances. 3437db96d56Sopenharmony_ci 3447db96d56Sopenharmony_ci 3457db96d56Sopenharmony_ci.. class:: WSGIRequestHandler(request, client_address, server) 3467db96d56Sopenharmony_ci 3477db96d56Sopenharmony_ci Create an HTTP handler for the given *request* (i.e. a socket), *client_address* 3487db96d56Sopenharmony_ci (a ``(host,port)`` tuple), and *server* (:class:`WSGIServer` instance). 3497db96d56Sopenharmony_ci 3507db96d56Sopenharmony_ci You do not need to create instances of this class directly; they are 3517db96d56Sopenharmony_ci automatically created as needed by :class:`WSGIServer` objects. You can, 3527db96d56Sopenharmony_ci however, subclass this class and supply it as a *handler_class* to the 3537db96d56Sopenharmony_ci :func:`make_server` function. Some possibly relevant methods for overriding in 3547db96d56Sopenharmony_ci subclasses: 3557db96d56Sopenharmony_ci 3567db96d56Sopenharmony_ci 3577db96d56Sopenharmony_ci .. method:: WSGIRequestHandler.get_environ() 3587db96d56Sopenharmony_ci 3597db96d56Sopenharmony_ci Return a :data:`~wsgiref.types.WSGIEnvironment` dictionary for a 3607db96d56Sopenharmony_ci request. The default 3617db96d56Sopenharmony_ci implementation copies the contents of the :class:`WSGIServer` object's 3627db96d56Sopenharmony_ci :attr:`base_environ` dictionary attribute and then adds various headers derived 3637db96d56Sopenharmony_ci from the HTTP request. Each call to this method should return a new dictionary 3647db96d56Sopenharmony_ci containing all of the relevant CGI environment variables as specified in 3657db96d56Sopenharmony_ci :pep:`3333`. 3667db96d56Sopenharmony_ci 3677db96d56Sopenharmony_ci 3687db96d56Sopenharmony_ci .. method:: WSGIRequestHandler.get_stderr() 3697db96d56Sopenharmony_ci 3707db96d56Sopenharmony_ci Return the object that should be used as the ``wsgi.errors`` stream. The default 3717db96d56Sopenharmony_ci implementation just returns ``sys.stderr``. 3727db96d56Sopenharmony_ci 3737db96d56Sopenharmony_ci 3747db96d56Sopenharmony_ci .. method:: WSGIRequestHandler.handle() 3757db96d56Sopenharmony_ci 3767db96d56Sopenharmony_ci Process the HTTP request. The default implementation creates a handler instance 3777db96d56Sopenharmony_ci using a :mod:`wsgiref.handlers` class to implement the actual WSGI application 3787db96d56Sopenharmony_ci interface. 3797db96d56Sopenharmony_ci 3807db96d56Sopenharmony_ci 3817db96d56Sopenharmony_ci:mod:`wsgiref.validate` --- WSGI conformance checker 3827db96d56Sopenharmony_ci---------------------------------------------------- 3837db96d56Sopenharmony_ci 3847db96d56Sopenharmony_ci.. module:: wsgiref.validate 3857db96d56Sopenharmony_ci :synopsis: WSGI conformance checker. 3867db96d56Sopenharmony_ci 3877db96d56Sopenharmony_ci 3887db96d56Sopenharmony_ciWhen creating new WSGI application objects, frameworks, servers, or middleware, 3897db96d56Sopenharmony_ciit can be useful to validate the new code's conformance using 3907db96d56Sopenharmony_ci:mod:`wsgiref.validate`. This module provides a function that creates WSGI 3917db96d56Sopenharmony_ciapplication objects that validate communications between a WSGI server or 3927db96d56Sopenharmony_cigateway and a WSGI application object, to check both sides for protocol 3937db96d56Sopenharmony_ciconformance. 3947db96d56Sopenharmony_ci 3957db96d56Sopenharmony_ciNote that this utility does not guarantee complete :pep:`3333` compliance; an 3967db96d56Sopenharmony_ciabsence of errors from this module does not necessarily mean that errors do not 3977db96d56Sopenharmony_ciexist. However, if this module does produce an error, then it is virtually 3987db96d56Sopenharmony_cicertain that either the server or application is not 100% compliant. 3997db96d56Sopenharmony_ci 4007db96d56Sopenharmony_ciThis module is based on the :mod:`paste.lint` module from Ian Bicking's "Python 4017db96d56Sopenharmony_ciPaste" library. 4027db96d56Sopenharmony_ci 4037db96d56Sopenharmony_ci 4047db96d56Sopenharmony_ci.. function:: validator(application) 4057db96d56Sopenharmony_ci 4067db96d56Sopenharmony_ci Wrap *application* and return a new WSGI application object. The returned 4077db96d56Sopenharmony_ci application will forward all requests to the original *application*, and will 4087db96d56Sopenharmony_ci check that both the *application* and the server invoking it are conforming to 4097db96d56Sopenharmony_ci the WSGI specification and to :rfc:`2616`. 4107db96d56Sopenharmony_ci 4117db96d56Sopenharmony_ci Any detected nonconformance results in an :exc:`AssertionError` being raised; 4127db96d56Sopenharmony_ci note, however, that how these errors are handled is server-dependent. For 4137db96d56Sopenharmony_ci example, :mod:`wsgiref.simple_server` and other servers based on 4147db96d56Sopenharmony_ci :mod:`wsgiref.handlers` (that don't override the error handling methods to do 4157db96d56Sopenharmony_ci something else) will simply output a message that an error has occurred, and 4167db96d56Sopenharmony_ci dump the traceback to ``sys.stderr`` or some other error stream. 4177db96d56Sopenharmony_ci 4187db96d56Sopenharmony_ci This wrapper may also generate output using the :mod:`warnings` module to 4197db96d56Sopenharmony_ci indicate behaviors that are questionable but which may not actually be 4207db96d56Sopenharmony_ci prohibited by :pep:`3333`. Unless they are suppressed using Python command-line 4217db96d56Sopenharmony_ci options or the :mod:`warnings` API, any such warnings will be written to 4227db96d56Sopenharmony_ci ``sys.stderr`` (*not* ``wsgi.errors``, unless they happen to be the same 4237db96d56Sopenharmony_ci object). 4247db96d56Sopenharmony_ci 4257db96d56Sopenharmony_ci Example usage:: 4267db96d56Sopenharmony_ci 4277db96d56Sopenharmony_ci from wsgiref.validate import validator 4287db96d56Sopenharmony_ci from wsgiref.simple_server import make_server 4297db96d56Sopenharmony_ci 4307db96d56Sopenharmony_ci # Our callable object which is intentionally not compliant to the 4317db96d56Sopenharmony_ci # standard, so the validator is going to break 4327db96d56Sopenharmony_ci def simple_app(environ, start_response): 4337db96d56Sopenharmony_ci status = '200 OK' # HTTP Status 4347db96d56Sopenharmony_ci headers = [('Content-type', 'text/plain')] # HTTP Headers 4357db96d56Sopenharmony_ci start_response(status, headers) 4367db96d56Sopenharmony_ci 4377db96d56Sopenharmony_ci # This is going to break because we need to return a list, and 4387db96d56Sopenharmony_ci # the validator is going to inform us 4397db96d56Sopenharmony_ci return b"Hello World" 4407db96d56Sopenharmony_ci 4417db96d56Sopenharmony_ci # This is the application wrapped in a validator 4427db96d56Sopenharmony_ci validator_app = validator(simple_app) 4437db96d56Sopenharmony_ci 4447db96d56Sopenharmony_ci with make_server('', 8000, validator_app) as httpd: 4457db96d56Sopenharmony_ci print("Listening on port 8000....") 4467db96d56Sopenharmony_ci httpd.serve_forever() 4477db96d56Sopenharmony_ci 4487db96d56Sopenharmony_ci 4497db96d56Sopenharmony_ci:mod:`wsgiref.handlers` -- server/gateway base classes 4507db96d56Sopenharmony_ci------------------------------------------------------ 4517db96d56Sopenharmony_ci 4527db96d56Sopenharmony_ci.. module:: wsgiref.handlers 4537db96d56Sopenharmony_ci :synopsis: WSGI server/gateway base classes. 4547db96d56Sopenharmony_ci 4557db96d56Sopenharmony_ci 4567db96d56Sopenharmony_ciThis module provides base handler classes for implementing WSGI servers and 4577db96d56Sopenharmony_cigateways. These base classes handle most of the work of communicating with a 4587db96d56Sopenharmony_ciWSGI application, as long as they are given a CGI-like environment, along with 4597db96d56Sopenharmony_ciinput, output, and error streams. 4607db96d56Sopenharmony_ci 4617db96d56Sopenharmony_ci 4627db96d56Sopenharmony_ci.. class:: CGIHandler() 4637db96d56Sopenharmony_ci 4647db96d56Sopenharmony_ci CGI-based invocation via ``sys.stdin``, ``sys.stdout``, ``sys.stderr`` and 4657db96d56Sopenharmony_ci ``os.environ``. This is useful when you have a WSGI application and want to run 4667db96d56Sopenharmony_ci it as a CGI script. Simply invoke ``CGIHandler().run(app)``, where ``app`` is 4677db96d56Sopenharmony_ci the WSGI application object you wish to invoke. 4687db96d56Sopenharmony_ci 4697db96d56Sopenharmony_ci This class is a subclass of :class:`BaseCGIHandler` that sets ``wsgi.run_once`` 4707db96d56Sopenharmony_ci to true, ``wsgi.multithread`` to false, and ``wsgi.multiprocess`` to true, and 4717db96d56Sopenharmony_ci always uses :mod:`sys` and :mod:`os` to obtain the necessary CGI streams and 4727db96d56Sopenharmony_ci environment. 4737db96d56Sopenharmony_ci 4747db96d56Sopenharmony_ci 4757db96d56Sopenharmony_ci.. class:: IISCGIHandler() 4767db96d56Sopenharmony_ci 4777db96d56Sopenharmony_ci A specialized alternative to :class:`CGIHandler`, for use when deploying on 4787db96d56Sopenharmony_ci Microsoft's IIS web server, without having set the config allowPathInfo 4797db96d56Sopenharmony_ci option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7). 4807db96d56Sopenharmony_ci 4817db96d56Sopenharmony_ci By default, IIS gives a ``PATH_INFO`` that duplicates the ``SCRIPT_NAME`` at 4827db96d56Sopenharmony_ci the front, causing problems for WSGI applications that wish to implement 4837db96d56Sopenharmony_ci routing. This handler strips any such duplicated path. 4847db96d56Sopenharmony_ci 4857db96d56Sopenharmony_ci IIS can be configured to pass the correct ``PATH_INFO``, but this causes 4867db96d56Sopenharmony_ci another bug where ``PATH_TRANSLATED`` is wrong. Luckily this variable is 4877db96d56Sopenharmony_ci rarely used and is not guaranteed by WSGI. On IIS<7, though, the 4887db96d56Sopenharmony_ci setting can only be made on a vhost level, affecting all other script 4897db96d56Sopenharmony_ci mappings, many of which break when exposed to the ``PATH_TRANSLATED`` bug. 4907db96d56Sopenharmony_ci For this reason IIS<7 is almost never deployed with the fix (Even IIS7 4917db96d56Sopenharmony_ci rarely uses it because there is still no UI for it.). 4927db96d56Sopenharmony_ci 4937db96d56Sopenharmony_ci There is no way for CGI code to tell whether the option was set, so a 4947db96d56Sopenharmony_ci separate handler class is provided. It is used in the same way as 4957db96d56Sopenharmony_ci :class:`CGIHandler`, i.e., by calling ``IISCGIHandler().run(app)``, where 4967db96d56Sopenharmony_ci ``app`` is the WSGI application object you wish to invoke. 4977db96d56Sopenharmony_ci 4987db96d56Sopenharmony_ci .. versionadded:: 3.2 4997db96d56Sopenharmony_ci 5007db96d56Sopenharmony_ci 5017db96d56Sopenharmony_ci.. class:: BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False) 5027db96d56Sopenharmony_ci 5037db96d56Sopenharmony_ci Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and 5047db96d56Sopenharmony_ci :mod:`os` modules, the CGI environment and I/O streams are specified explicitly. 5057db96d56Sopenharmony_ci The *multithread* and *multiprocess* values are used to set the 5067db96d56Sopenharmony_ci ``wsgi.multithread`` and ``wsgi.multiprocess`` flags for any applications run by 5077db96d56Sopenharmony_ci the handler instance. 5087db96d56Sopenharmony_ci 5097db96d56Sopenharmony_ci This class is a subclass of :class:`SimpleHandler` intended for use with 5107db96d56Sopenharmony_ci software other than HTTP "origin servers". If you are writing a gateway 5117db96d56Sopenharmony_ci protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a 5127db96d56Sopenharmony_ci ``Status:`` header to send an HTTP status, you probably want to subclass this 5137db96d56Sopenharmony_ci instead of :class:`SimpleHandler`. 5147db96d56Sopenharmony_ci 5157db96d56Sopenharmony_ci 5167db96d56Sopenharmony_ci.. class:: SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False) 5177db96d56Sopenharmony_ci 5187db96d56Sopenharmony_ci Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin 5197db96d56Sopenharmony_ci servers. If you are writing an HTTP server implementation, you will probably 5207db96d56Sopenharmony_ci want to subclass this instead of :class:`BaseCGIHandler`. 5217db96d56Sopenharmony_ci 5227db96d56Sopenharmony_ci This class is a subclass of :class:`BaseHandler`. It overrides the 5237db96d56Sopenharmony_ci :meth:`__init__`, :meth:`get_stdin`, :meth:`get_stderr`, :meth:`add_cgi_vars`, 5247db96d56Sopenharmony_ci :meth:`_write`, and :meth:`_flush` methods to support explicitly setting the 5257db96d56Sopenharmony_ci environment and streams via the constructor. The supplied environment and 5267db96d56Sopenharmony_ci streams are stored in the :attr:`stdin`, :attr:`stdout`, :attr:`stderr`, and 5277db96d56Sopenharmony_ci :attr:`environ` attributes. 5287db96d56Sopenharmony_ci 5297db96d56Sopenharmony_ci The :meth:`~io.BufferedIOBase.write` method of *stdout* should write 5307db96d56Sopenharmony_ci each chunk in full, like :class:`io.BufferedIOBase`. 5317db96d56Sopenharmony_ci 5327db96d56Sopenharmony_ci 5337db96d56Sopenharmony_ci.. class:: BaseHandler() 5347db96d56Sopenharmony_ci 5357db96d56Sopenharmony_ci This is an abstract base class for running WSGI applications. Each instance 5367db96d56Sopenharmony_ci will handle a single HTTP request, although in principle you could create a 5377db96d56Sopenharmony_ci subclass that was reusable for multiple requests. 5387db96d56Sopenharmony_ci 5397db96d56Sopenharmony_ci :class:`BaseHandler` instances have only one method intended for external use: 5407db96d56Sopenharmony_ci 5417db96d56Sopenharmony_ci 5427db96d56Sopenharmony_ci .. method:: BaseHandler.run(app) 5437db96d56Sopenharmony_ci 5447db96d56Sopenharmony_ci Run the specified WSGI application, *app*. 5457db96d56Sopenharmony_ci 5467db96d56Sopenharmony_ci All of the other :class:`BaseHandler` methods are invoked by this method in the 5477db96d56Sopenharmony_ci process of running the application, and thus exist primarily to allow 5487db96d56Sopenharmony_ci customizing the process. 5497db96d56Sopenharmony_ci 5507db96d56Sopenharmony_ci The following methods MUST be overridden in a subclass: 5517db96d56Sopenharmony_ci 5527db96d56Sopenharmony_ci 5537db96d56Sopenharmony_ci .. method:: BaseHandler._write(data) 5547db96d56Sopenharmony_ci 5557db96d56Sopenharmony_ci Buffer the bytes *data* for transmission to the client. It's okay if this 5567db96d56Sopenharmony_ci method actually transmits the data; :class:`BaseHandler` just separates write 5577db96d56Sopenharmony_ci and flush operations for greater efficiency when the underlying system actually 5587db96d56Sopenharmony_ci has such a distinction. 5597db96d56Sopenharmony_ci 5607db96d56Sopenharmony_ci 5617db96d56Sopenharmony_ci .. method:: BaseHandler._flush() 5627db96d56Sopenharmony_ci 5637db96d56Sopenharmony_ci Force buffered data to be transmitted to the client. It's okay if this method 5647db96d56Sopenharmony_ci is a no-op (i.e., if :meth:`_write` actually sends the data). 5657db96d56Sopenharmony_ci 5667db96d56Sopenharmony_ci 5677db96d56Sopenharmony_ci .. method:: BaseHandler.get_stdin() 5687db96d56Sopenharmony_ci 5697db96d56Sopenharmony_ci Return an object compatible with :class:`~wsgiref.types.InputStream` 5707db96d56Sopenharmony_ci suitable for use as the ``wsgi.input`` of the 5717db96d56Sopenharmony_ci request currently being processed. 5727db96d56Sopenharmony_ci 5737db96d56Sopenharmony_ci 5747db96d56Sopenharmony_ci .. method:: BaseHandler.get_stderr() 5757db96d56Sopenharmony_ci 5767db96d56Sopenharmony_ci Return an object compatible with :class:`~wsgiref.types.ErrorStream` 5777db96d56Sopenharmony_ci suitable for use as the ``wsgi.errors`` of the 5787db96d56Sopenharmony_ci request currently being processed. 5797db96d56Sopenharmony_ci 5807db96d56Sopenharmony_ci 5817db96d56Sopenharmony_ci .. method:: BaseHandler.add_cgi_vars() 5827db96d56Sopenharmony_ci 5837db96d56Sopenharmony_ci Insert CGI variables for the current request into the :attr:`environ` attribute. 5847db96d56Sopenharmony_ci 5857db96d56Sopenharmony_ci Here are some other methods and attributes you may wish to override. This list 5867db96d56Sopenharmony_ci is only a summary, however, and does not include every method that can be 5877db96d56Sopenharmony_ci overridden. You should consult the docstrings and source code for additional 5887db96d56Sopenharmony_ci information before attempting to create a customized :class:`BaseHandler` 5897db96d56Sopenharmony_ci subclass. 5907db96d56Sopenharmony_ci 5917db96d56Sopenharmony_ci Attributes and methods for customizing the WSGI environment: 5927db96d56Sopenharmony_ci 5937db96d56Sopenharmony_ci 5947db96d56Sopenharmony_ci .. attribute:: BaseHandler.wsgi_multithread 5957db96d56Sopenharmony_ci 5967db96d56Sopenharmony_ci The value to be used for the ``wsgi.multithread`` environment variable. It 5977db96d56Sopenharmony_ci defaults to true in :class:`BaseHandler`, but may have a different default (or 5987db96d56Sopenharmony_ci be set by the constructor) in the other subclasses. 5997db96d56Sopenharmony_ci 6007db96d56Sopenharmony_ci 6017db96d56Sopenharmony_ci .. attribute:: BaseHandler.wsgi_multiprocess 6027db96d56Sopenharmony_ci 6037db96d56Sopenharmony_ci The value to be used for the ``wsgi.multiprocess`` environment variable. It 6047db96d56Sopenharmony_ci defaults to true in :class:`BaseHandler`, but may have a different default (or 6057db96d56Sopenharmony_ci be set by the constructor) in the other subclasses. 6067db96d56Sopenharmony_ci 6077db96d56Sopenharmony_ci 6087db96d56Sopenharmony_ci .. attribute:: BaseHandler.wsgi_run_once 6097db96d56Sopenharmony_ci 6107db96d56Sopenharmony_ci The value to be used for the ``wsgi.run_once`` environment variable. It 6117db96d56Sopenharmony_ci defaults to false in :class:`BaseHandler`, but :class:`CGIHandler` sets it to 6127db96d56Sopenharmony_ci true by default. 6137db96d56Sopenharmony_ci 6147db96d56Sopenharmony_ci 6157db96d56Sopenharmony_ci .. attribute:: BaseHandler.os_environ 6167db96d56Sopenharmony_ci 6177db96d56Sopenharmony_ci The default environment variables to be included in every request's WSGI 6187db96d56Sopenharmony_ci environment. By default, this is a copy of ``os.environ`` at the time that 6197db96d56Sopenharmony_ci :mod:`wsgiref.handlers` was imported, but subclasses can either create their own 6207db96d56Sopenharmony_ci at the class or instance level. Note that the dictionary should be considered 6217db96d56Sopenharmony_ci read-only, since the default value is shared between multiple classes and 6227db96d56Sopenharmony_ci instances. 6237db96d56Sopenharmony_ci 6247db96d56Sopenharmony_ci 6257db96d56Sopenharmony_ci .. attribute:: BaseHandler.server_software 6267db96d56Sopenharmony_ci 6277db96d56Sopenharmony_ci If the :attr:`origin_server` attribute is set, this attribute's value is used to 6287db96d56Sopenharmony_ci set the default ``SERVER_SOFTWARE`` WSGI environment variable, and also to set a 6297db96d56Sopenharmony_ci default ``Server:`` header in HTTP responses. It is ignored for handlers (such 6307db96d56Sopenharmony_ci as :class:`BaseCGIHandler` and :class:`CGIHandler`) that are not HTTP origin 6317db96d56Sopenharmony_ci servers. 6327db96d56Sopenharmony_ci 6337db96d56Sopenharmony_ci .. versionchanged:: 3.3 6347db96d56Sopenharmony_ci The term "Python" is replaced with implementation specific term like 6357db96d56Sopenharmony_ci "CPython", "Jython" etc. 6367db96d56Sopenharmony_ci 6377db96d56Sopenharmony_ci .. method:: BaseHandler.get_scheme() 6387db96d56Sopenharmony_ci 6397db96d56Sopenharmony_ci Return the URL scheme being used for the current request. The default 6407db96d56Sopenharmony_ci implementation uses the :func:`guess_scheme` function from :mod:`wsgiref.util` 6417db96d56Sopenharmony_ci to guess whether the scheme should be "http" or "https", based on the current 6427db96d56Sopenharmony_ci request's :attr:`environ` variables. 6437db96d56Sopenharmony_ci 6447db96d56Sopenharmony_ci 6457db96d56Sopenharmony_ci .. method:: BaseHandler.setup_environ() 6467db96d56Sopenharmony_ci 6477db96d56Sopenharmony_ci Set the :attr:`environ` attribute to a fully populated WSGI environment. The 6487db96d56Sopenharmony_ci default implementation uses all of the above methods and attributes, plus the 6497db96d56Sopenharmony_ci :meth:`get_stdin`, :meth:`get_stderr`, and :meth:`add_cgi_vars` methods and the 6507db96d56Sopenharmony_ci :attr:`wsgi_file_wrapper` attribute. It also inserts a ``SERVER_SOFTWARE`` key 6517db96d56Sopenharmony_ci if not present, as long as the :attr:`origin_server` attribute is a true value 6527db96d56Sopenharmony_ci and the :attr:`server_software` attribute is set. 6537db96d56Sopenharmony_ci 6547db96d56Sopenharmony_ci Methods and attributes for customizing exception handling: 6557db96d56Sopenharmony_ci 6567db96d56Sopenharmony_ci 6577db96d56Sopenharmony_ci .. method:: BaseHandler.log_exception(exc_info) 6587db96d56Sopenharmony_ci 6597db96d56Sopenharmony_ci Log the *exc_info* tuple in the server log. *exc_info* is a ``(type, value, 6607db96d56Sopenharmony_ci traceback)`` tuple. The default implementation simply writes the traceback to 6617db96d56Sopenharmony_ci the request's ``wsgi.errors`` stream and flushes it. Subclasses can override 6627db96d56Sopenharmony_ci this method to change the format or retarget the output, mail the traceback to 6637db96d56Sopenharmony_ci an administrator, or whatever other action may be deemed suitable. 6647db96d56Sopenharmony_ci 6657db96d56Sopenharmony_ci 6667db96d56Sopenharmony_ci .. attribute:: BaseHandler.traceback_limit 6677db96d56Sopenharmony_ci 6687db96d56Sopenharmony_ci The maximum number of frames to include in tracebacks output by the default 6697db96d56Sopenharmony_ci :meth:`log_exception` method. If ``None``, all frames are included. 6707db96d56Sopenharmony_ci 6717db96d56Sopenharmony_ci 6727db96d56Sopenharmony_ci .. method:: BaseHandler.error_output(environ, start_response) 6737db96d56Sopenharmony_ci 6747db96d56Sopenharmony_ci This method is a WSGI application to generate an error page for the user. It is 6757db96d56Sopenharmony_ci only invoked if an error occurs before headers are sent to the client. 6767db96d56Sopenharmony_ci 6777db96d56Sopenharmony_ci This method can access the current error using ``sys.exception()``, 6787db96d56Sopenharmony_ci and should pass that information to *start_response* when calling it (as 6797db96d56Sopenharmony_ci described in the "Error Handling" section of :pep:`3333`). 6807db96d56Sopenharmony_ci 6817db96d56Sopenharmony_ci The default implementation just uses the :attr:`error_status`, 6827db96d56Sopenharmony_ci :attr:`error_headers`, and :attr:`error_body` attributes to generate an output 6837db96d56Sopenharmony_ci page. Subclasses can override this to produce more dynamic error output. 6847db96d56Sopenharmony_ci 6857db96d56Sopenharmony_ci Note, however, that it's not recommended from a security perspective to spit out 6867db96d56Sopenharmony_ci diagnostics to any old user; ideally, you should have to do something special to 6877db96d56Sopenharmony_ci enable diagnostic output, which is why the default implementation doesn't 6887db96d56Sopenharmony_ci include any. 6897db96d56Sopenharmony_ci 6907db96d56Sopenharmony_ci 6917db96d56Sopenharmony_ci .. attribute:: BaseHandler.error_status 6927db96d56Sopenharmony_ci 6937db96d56Sopenharmony_ci The HTTP status used for error responses. This should be a status string as 6947db96d56Sopenharmony_ci defined in :pep:`3333`; it defaults to a 500 code and message. 6957db96d56Sopenharmony_ci 6967db96d56Sopenharmony_ci 6977db96d56Sopenharmony_ci .. attribute:: BaseHandler.error_headers 6987db96d56Sopenharmony_ci 6997db96d56Sopenharmony_ci The HTTP headers used for error responses. This should be a list of WSGI 7007db96d56Sopenharmony_ci response headers (``(name, value)`` tuples), as described in :pep:`3333`. The 7017db96d56Sopenharmony_ci default list just sets the content type to ``text/plain``. 7027db96d56Sopenharmony_ci 7037db96d56Sopenharmony_ci 7047db96d56Sopenharmony_ci .. attribute:: BaseHandler.error_body 7057db96d56Sopenharmony_ci 7067db96d56Sopenharmony_ci The error response body. This should be an HTTP response body bytestring. It 7077db96d56Sopenharmony_ci defaults to the plain text, "A server error occurred. Please contact the 7087db96d56Sopenharmony_ci administrator." 7097db96d56Sopenharmony_ci 7107db96d56Sopenharmony_ci Methods and attributes for :pep:`3333`'s "Optional Platform-Specific File 7117db96d56Sopenharmony_ci Handling" feature: 7127db96d56Sopenharmony_ci 7137db96d56Sopenharmony_ci 7147db96d56Sopenharmony_ci .. attribute:: BaseHandler.wsgi_file_wrapper 7157db96d56Sopenharmony_ci 7167db96d56Sopenharmony_ci A ``wsgi.file_wrapper`` factory, compatible with 7177db96d56Sopenharmony_ci :class:`wsgiref.types.FileWrapper`, or ``None``. The default value 7187db96d56Sopenharmony_ci of this attribute is the :class:`wsgiref.util.FileWrapper` class. 7197db96d56Sopenharmony_ci 7207db96d56Sopenharmony_ci 7217db96d56Sopenharmony_ci .. method:: BaseHandler.sendfile() 7227db96d56Sopenharmony_ci 7237db96d56Sopenharmony_ci Override to implement platform-specific file transmission. This method is 7247db96d56Sopenharmony_ci called only if the application's return value is an instance of the class 7257db96d56Sopenharmony_ci specified by the :attr:`wsgi_file_wrapper` attribute. It should return a true 7267db96d56Sopenharmony_ci value if it was able to successfully transmit the file, so that the default 7277db96d56Sopenharmony_ci transmission code will not be executed. The default implementation of this 7287db96d56Sopenharmony_ci method just returns a false value. 7297db96d56Sopenharmony_ci 7307db96d56Sopenharmony_ci Miscellaneous methods and attributes: 7317db96d56Sopenharmony_ci 7327db96d56Sopenharmony_ci 7337db96d56Sopenharmony_ci .. attribute:: BaseHandler.origin_server 7347db96d56Sopenharmony_ci 7357db96d56Sopenharmony_ci This attribute should be set to a true value if the handler's :meth:`_write` and 7367db96d56Sopenharmony_ci :meth:`_flush` are being used to communicate directly to the client, rather than 7377db96d56Sopenharmony_ci via a CGI-like gateway protocol that wants the HTTP status in a special 7387db96d56Sopenharmony_ci ``Status:`` header. 7397db96d56Sopenharmony_ci 7407db96d56Sopenharmony_ci This attribute's default value is true in :class:`BaseHandler`, but false in 7417db96d56Sopenharmony_ci :class:`BaseCGIHandler` and :class:`CGIHandler`. 7427db96d56Sopenharmony_ci 7437db96d56Sopenharmony_ci 7447db96d56Sopenharmony_ci .. attribute:: BaseHandler.http_version 7457db96d56Sopenharmony_ci 7467db96d56Sopenharmony_ci If :attr:`origin_server` is true, this string attribute is used to set the HTTP 7477db96d56Sopenharmony_ci version of the response set to the client. It defaults to ``"1.0"``. 7487db96d56Sopenharmony_ci 7497db96d56Sopenharmony_ci 7507db96d56Sopenharmony_ci.. function:: read_environ() 7517db96d56Sopenharmony_ci 7527db96d56Sopenharmony_ci Transcode CGI variables from ``os.environ`` to :pep:`3333` "bytes in unicode" 7537db96d56Sopenharmony_ci strings, returning a new dictionary. This function is used by 7547db96d56Sopenharmony_ci :class:`CGIHandler` and :class:`IISCGIHandler` in place of directly using 7557db96d56Sopenharmony_ci ``os.environ``, which is not necessarily WSGI-compliant on all platforms 7567db96d56Sopenharmony_ci and web servers using Python 3 -- specifically, ones where the OS's 7577db96d56Sopenharmony_ci actual environment is Unicode (i.e. Windows), or ones where the environment 7587db96d56Sopenharmony_ci is bytes, but the system encoding used by Python to decode it is anything 7597db96d56Sopenharmony_ci other than ISO-8859-1 (e.g. Unix systems using UTF-8). 7607db96d56Sopenharmony_ci 7617db96d56Sopenharmony_ci If you are implementing a CGI-based handler of your own, you probably want 7627db96d56Sopenharmony_ci to use this routine instead of just copying values out of ``os.environ`` 7637db96d56Sopenharmony_ci directly. 7647db96d56Sopenharmony_ci 7657db96d56Sopenharmony_ci .. versionadded:: 3.2 7667db96d56Sopenharmony_ci 7677db96d56Sopenharmony_ci 7687db96d56Sopenharmony_ci:mod:`wsgiref.types` -- WSGI types for static type checking 7697db96d56Sopenharmony_ci----------------------------------------------------------- 7707db96d56Sopenharmony_ci 7717db96d56Sopenharmony_ci.. module:: wsgiref.types 7727db96d56Sopenharmony_ci :synopsis: WSGI types for static type checking 7737db96d56Sopenharmony_ci 7747db96d56Sopenharmony_ci 7757db96d56Sopenharmony_ciThis module provides various types for static type checking as described 7767db96d56Sopenharmony_ciin :pep:`3333`. 7777db96d56Sopenharmony_ci 7787db96d56Sopenharmony_ci.. versionadded:: 3.11 7797db96d56Sopenharmony_ci 7807db96d56Sopenharmony_ci 7817db96d56Sopenharmony_ci.. class:: StartResponse() 7827db96d56Sopenharmony_ci 7837db96d56Sopenharmony_ci A :class:`typing.Protocol` describing `start_response() 7847db96d56Sopenharmony_ci <https://peps.python.org/pep-3333/#the-start-response-callable>`_ 7857db96d56Sopenharmony_ci callables (:pep:`3333`). 7867db96d56Sopenharmony_ci 7877db96d56Sopenharmony_ci.. data:: WSGIEnvironment 7887db96d56Sopenharmony_ci 7897db96d56Sopenharmony_ci A type alias describing a WSGI environment dictionary. 7907db96d56Sopenharmony_ci 7917db96d56Sopenharmony_ci.. data:: WSGIApplication 7927db96d56Sopenharmony_ci 7937db96d56Sopenharmony_ci A type alias describing a WSGI application callable. 7947db96d56Sopenharmony_ci 7957db96d56Sopenharmony_ci.. class:: InputStream() 7967db96d56Sopenharmony_ci 7977db96d56Sopenharmony_ci A :class:`typing.Protocol` describing a `WSGI Input Stream 7987db96d56Sopenharmony_ci <https://peps.python.org/pep-3333/#input-and-error-streams>`_. 7997db96d56Sopenharmony_ci 8007db96d56Sopenharmony_ci.. class:: ErrorStream() 8017db96d56Sopenharmony_ci 8027db96d56Sopenharmony_ci A :class:`typing.Protocol` describing a `WSGI Error Stream 8037db96d56Sopenharmony_ci <https://peps.python.org/pep-3333/#input-and-error-streams>`_. 8047db96d56Sopenharmony_ci 8057db96d56Sopenharmony_ci.. class:: FileWrapper() 8067db96d56Sopenharmony_ci 8077db96d56Sopenharmony_ci A :class:`typing.Protocol` describing a `file wrapper 8087db96d56Sopenharmony_ci <https://peps.python.org/pep-3333/#optional-platform-specific-file-handling>`_. 8097db96d56Sopenharmony_ci See :class:`wsgiref.util.FileWrapper` for a concrete implementation of this 8107db96d56Sopenharmony_ci protocol. 8117db96d56Sopenharmony_ci 8127db96d56Sopenharmony_ci 8137db96d56Sopenharmony_ciExamples 8147db96d56Sopenharmony_ci-------- 8157db96d56Sopenharmony_ci 8167db96d56Sopenharmony_ciThis is a working "Hello World" WSGI application:: 8177db96d56Sopenharmony_ci 8187db96d56Sopenharmony_ci """ 8197db96d56Sopenharmony_ci Every WSGI application must have an application object - a callable 8207db96d56Sopenharmony_ci object that accepts two arguments. For that purpose, we're going to 8217db96d56Sopenharmony_ci use a function (note that you're not limited to a function, you can 8227db96d56Sopenharmony_ci use a class for example). The first argument passed to the function 8237db96d56Sopenharmony_ci is a dictionary containing CGI-style environment variables and the 8247db96d56Sopenharmony_ci second variable is the callable object. 8257db96d56Sopenharmony_ci """ 8267db96d56Sopenharmony_ci from wsgiref.simple_server import make_server 8277db96d56Sopenharmony_ci 8287db96d56Sopenharmony_ci 8297db96d56Sopenharmony_ci def hello_world_app(environ, start_response): 8307db96d56Sopenharmony_ci status = "200 OK" # HTTP Status 8317db96d56Sopenharmony_ci headers = [("Content-type", "text/plain; charset=utf-8")] # HTTP Headers 8327db96d56Sopenharmony_ci start_response(status, headers) 8337db96d56Sopenharmony_ci 8347db96d56Sopenharmony_ci # The returned object is going to be printed 8357db96d56Sopenharmony_ci return [b"Hello World"] 8367db96d56Sopenharmony_ci 8377db96d56Sopenharmony_ci with make_server("", 8000, hello_world_app) as httpd: 8387db96d56Sopenharmony_ci print("Serving on port 8000...") 8397db96d56Sopenharmony_ci 8407db96d56Sopenharmony_ci # Serve until process is killed 8417db96d56Sopenharmony_ci httpd.serve_forever() 8427db96d56Sopenharmony_ci 8437db96d56Sopenharmony_ci 8447db96d56Sopenharmony_ci 8457db96d56Sopenharmony_ciExample of a WSGI application serving the current directory, accept optional 8467db96d56Sopenharmony_cidirectory and port number (default: 8000) on the command line:: 8477db96d56Sopenharmony_ci 8487db96d56Sopenharmony_ci """ 8497db96d56Sopenharmony_ci Small wsgiref based web server. Takes a path to serve from and an 8507db96d56Sopenharmony_ci optional port number (defaults to 8000), then tries to serve files. 8517db96d56Sopenharmony_ci MIME types are guessed from the file names, 404 errors are raised 8527db96d56Sopenharmony_ci if the file is not found. 8537db96d56Sopenharmony_ci """ 8547db96d56Sopenharmony_ci import mimetypes 8557db96d56Sopenharmony_ci import os 8567db96d56Sopenharmony_ci import sys 8577db96d56Sopenharmony_ci from wsgiref import simple_server, util 8587db96d56Sopenharmony_ci 8597db96d56Sopenharmony_ci 8607db96d56Sopenharmony_ci def app(environ, respond): 8617db96d56Sopenharmony_ci # Get the file name and MIME type 8627db96d56Sopenharmony_ci fn = os.path.join(path, environ["PATH_INFO"][1:]) 8637db96d56Sopenharmony_ci if "." not in fn.split(os.path.sep)[-1]: 8647db96d56Sopenharmony_ci fn = os.path.join(fn, "index.html") 8657db96d56Sopenharmony_ci mime_type = mimetypes.guess_type(fn)[0] 8667db96d56Sopenharmony_ci 8677db96d56Sopenharmony_ci # Return 200 OK if file exists, otherwise 404 Not Found 8687db96d56Sopenharmony_ci if os.path.exists(fn): 8697db96d56Sopenharmony_ci respond("200 OK", [("Content-Type", mime_type)]) 8707db96d56Sopenharmony_ci return util.FileWrapper(open(fn, "rb")) 8717db96d56Sopenharmony_ci else: 8727db96d56Sopenharmony_ci respond("404 Not Found", [("Content-Type", "text/plain")]) 8737db96d56Sopenharmony_ci return [b"not found"] 8747db96d56Sopenharmony_ci 8757db96d56Sopenharmony_ci 8767db96d56Sopenharmony_ci if __name__ == "__main__": 8777db96d56Sopenharmony_ci # Get the path and port from command-line arguments 8787db96d56Sopenharmony_ci path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd() 8797db96d56Sopenharmony_ci port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 8807db96d56Sopenharmony_ci 8817db96d56Sopenharmony_ci # Make and start the server until control-c 8827db96d56Sopenharmony_ci httpd = simple_server.make_server("", port, app) 8837db96d56Sopenharmony_ci print(f"Serving {path} on port {port}, control-C to stop") 8847db96d56Sopenharmony_ci try: 8857db96d56Sopenharmony_ci httpd.serve_forever() 8867db96d56Sopenharmony_ci except KeyboardInterrupt: 8877db96d56Sopenharmony_ci print("Shutting down.") 8887db96d56Sopenharmony_ci httpd.server_close() 8897db96d56Sopenharmony_ci 8907db96d56Sopenharmony_ci 891