summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fwsgiref.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/library%2Fwsgiref.html')
-rw-r--r--devdocs/python~3.12/library%2Fwsgiref.html298
1 files changed, 298 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fwsgiref.html b/devdocs/python~3.12/library%2Fwsgiref.html
new file mode 100644
index 00000000..46d894fb
--- /dev/null
+++ b/devdocs/python~3.12/library%2Fwsgiref.html
@@ -0,0 +1,298 @@
+ <span id="wsgiref-wsgi-utilities-and-reference-implementation"></span><h1>wsgiref — WSGI Utilities and Reference Implementation</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/wsgiref">Lib/wsgiref</a></p> <p>The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. Having a standard interface makes it easy to use an application that supports WSGI with a number of different web servers.</p> <p>Only authors of web servers and programming frameworks need to know every detail and corner case of the WSGI design. You don’t need to understand every detail of WSGI just to install a WSGI application or to write a web application using an existing framework.</p> <p><a class="reference internal" href="#module-wsgiref" title="wsgiref: WSGI Utilities and Reference Implementation."><code>wsgiref</code></a> is a reference implementation of the WSGI specification that can be used to add WSGI support to a web server or framework. It provides utilities for manipulating WSGI environment variables and response headers, base classes for implementing WSGI servers, a demo HTTP server that serves WSGI applications, types for static type checking, and a validation tool that checks WSGI servers and applications for conformance to the WSGI specification (<span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>).</p> <p>See <a class="reference external" href="https://wsgi.readthedocs.io/">wsgi.readthedocs.io</a> for more information about WSGI, and links to tutorials and other resources.</p> <section id="module-wsgiref.util"> <span id="wsgiref-util-wsgi-environment-utilities"></span><h2>wsgiref.util – WSGI environment utilities</h2> <p>This module provides a variety of utility functions for working with WSGI environments. A WSGI environment is a dictionary containing HTTP request variables as described in <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>. All of the functions taking an <em>environ</em> parameter expect a WSGI-compliant dictionary to be supplied; please see <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a> for a detailed specification and <a class="reference internal" href="#wsgiref.types.WSGIEnvironment" title="wsgiref.types.WSGIEnvironment"><code>WSGIEnvironment</code></a> for a type alias that can be used in type annotations.</p> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.util.guess_scheme">
+<code>wsgiref.util.guess_scheme(environ)</code> </dt> <dd>
+<p>Return a guess for whether <code>wsgi.url_scheme</code> should be “http” or “https”, by checking for a <code>HTTPS</code> environment variable in the <em>environ</em> dictionary. The return value is a string.</p> <p>This function is useful when creating a gateway that wraps CGI or a CGI-like protocol such as FastCGI. Typically, servers providing such protocols will include a <code>HTTPS</code> variable with a value of “1”, “yes”, or “on” when a request is received via SSL. So, this function returns “https” if such a value is found, and “http” otherwise.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.util.request_uri">
+<code>wsgiref.util.request_uri(environ, include_query=True)</code> </dt> <dd>
+<p>Return the full request URI, optionally including the query string, using the algorithm found in the “URL Reconstruction” section of <span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>. If <em>include_query</em> is false, the query string is not included in the resulting URI.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.util.application_uri">
+<code>wsgiref.util.application_uri(environ)</code> </dt> <dd>
+<p>Similar to <a class="reference internal" href="#wsgiref.util.request_uri" title="wsgiref.util.request_uri"><code>request_uri()</code></a>, except that the <code>PATH_INFO</code> and <code>QUERY_STRING</code> variables are ignored. The result is the base URI of the application object addressed by the request.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.util.shift_path_info">
+<code>wsgiref.util.shift_path_info(environ)</code> </dt> <dd>
+<p>Shift a single name from <code>PATH_INFO</code> to <code>SCRIPT_NAME</code> and return the name. The <em>environ</em> dictionary is <em>modified</em> in-place; use a copy if you need to keep the original <code>PATH_INFO</code> or <code>SCRIPT_NAME</code> intact.</p> <p>If there are no remaining path segments in <code>PATH_INFO</code>, <code>None</code> is returned.</p> <p>Typically, this routine is used to process each portion of a request URI path, for example to treat the path as a series of dictionary keys. This routine modifies the passed-in environment to make it suitable for invoking another WSGI application that is located at the target URI. For example, if there is a WSGI application at <code>/foo</code>, and the request URI path is <code>/foo/bar/baz</code>, and the WSGI application at <code>/foo</code> calls <a class="reference internal" href="#wsgiref.util.shift_path_info" title="wsgiref.util.shift_path_info"><code>shift_path_info()</code></a>, it will receive the string “bar”, and the environment will be updated to be suitable for passing to a WSGI application at <code>/foo/bar</code>. That is, <code>SCRIPT_NAME</code> will change from <code>/foo</code> to <code>/foo/bar</code>, and <code>PATH_INFO</code> will change from <code>/bar/baz</code> to <code>/baz</code>.</p> <p>When <code>PATH_INFO</code> is just a “/”, this routine returns an empty string and appends a trailing slash to <code>SCRIPT_NAME</code>, even though empty path segments are normally ignored, and <code>SCRIPT_NAME</code> doesn’t normally end in a slash. This is intentional behavior, to ensure that an application can tell the difference between URIs ending in <code>/x</code> from ones ending in <code>/x/</code> when using this routine to do object traversal.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.util.setup_testing_defaults">
+<code>wsgiref.util.setup_testing_defaults(environ)</code> </dt> <dd>
+<p>Update <em>environ</em> with trivial defaults for testing purposes.</p> <p>This routine adds various parameters required for WSGI, including <code>HTTP_HOST</code>, <code>SERVER_NAME</code>, <code>SERVER_PORT</code>, <code>REQUEST_METHOD</code>, <code>SCRIPT_NAME</code>, <code>PATH_INFO</code>, and all of the <span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>-defined <code>wsgi.*</code> variables. It only supplies default values, and does not replace any existing settings for these variables.</p> <p>This routine is intended to make it easier for unit tests of WSGI servers and applications to set up dummy environments. It should NOT be used by actual WSGI servers or applications, since the data is fake!</p> <p>Example usage:</p> <pre data-language="python">from wsgiref.util import setup_testing_defaults
+from wsgiref.simple_server import make_server
+
+# A relatively simple WSGI application. It's going to print out the
+# environment dictionary after being updated by setup_testing_defaults
+def simple_app(environ, start_response):
+ setup_testing_defaults(environ)
+
+ status = '200 OK'
+ headers = [('Content-type', 'text/plain; charset=utf-8')]
+
+ start_response(status, headers)
+
+ ret = [("%s: %s\n" % (key, value)).encode("utf-8")
+ for key, value in environ.items()]
+ return ret
+
+with make_server('', 8000, simple_app) as httpd:
+ print("Serving on port 8000...")
+ httpd.serve_forever()
+</pre> </dd>
+</dl> <p>In addition to the environment functions above, the <a class="reference internal" href="#module-wsgiref.util" title="wsgiref.util: WSGI environment utilities."><code>wsgiref.util</code></a> module also provides these miscellaneous utilities:</p> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.util.is_hop_by_hop">
+<code>wsgiref.util.is_hop_by_hop(header_name)</code> </dt> <dd>
+<p>Return <code>True</code> if ‘header_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined by <span class="target" id="index-5"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2616.html"><strong>RFC 2616</strong></a>.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.util.FileWrapper">
+<code>class wsgiref.util.FileWrapper(filelike, blksize=8192)</code> </dt> <dd>
+<p>A concrete implementation of the <a class="reference internal" href="#wsgiref.types.FileWrapper" title="wsgiref.types.FileWrapper"><code>wsgiref.types.FileWrapper</code></a> protocol used to convert a file-like object to an <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a>. The resulting objects are <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a>s. As the object is iterated over, the optional <em>blksize</em> parameter will be repeatedly passed to the <em>filelike</em> object’s <code>read()</code> method to obtain bytestrings to yield. When <code>read()</code> returns an empty bytestring, iteration is ended and is not resumable.</p> <p>If <em>filelike</em> has a <code>close()</code> method, the returned object will also have a <code>close()</code> method, and it will invoke the <em>filelike</em> object’s <code>close()</code> method when called.</p> <p>Example usage:</p> <pre data-language="python">from io import StringIO
+from wsgiref.util import FileWrapper
+
+# We're using a StringIO-buffer for as the file-like object
+filelike = StringIO("This is an example file-like object"*10)
+wrapper = FileWrapper(filelike, blksize=5)
+
+for chunk in wrapper:
+ print(chunk)
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Support for <a class="reference internal" href="../reference/datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a> method has been removed.</p> </div> </dd>
+</dl> </section> <section id="module-wsgiref.headers"> <span id="wsgiref-headers-wsgi-response-header-tools"></span><h2>wsgiref.headers – WSGI response header tools</h2> <p>This module provides a single class, <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code>Headers</code></a>, for convenient manipulation of WSGI response headers using a mapping-like interface.</p> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.headers.Headers">
+<code>class wsgiref.headers.Headers([headers])</code> </dt> <dd>
+<p>Create a mapping-like object wrapping <em>headers</em>, which must be a list of header name/value tuples as described in <span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>. The default value of <em>headers</em> is an empty list.</p> <p><a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code>Headers</code></a> objects support typical mapping operations including <a class="reference internal" href="../reference/datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a>, <a class="reference internal" href="stdtypes#dict.get" title="dict.get"><code>get()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__setitem__" title="object.__setitem__"><code>__setitem__()</code></a>, <a class="reference internal" href="stdtypes#dict.setdefault" title="dict.setdefault"><code>setdefault()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__delitem__" title="object.__delitem__"><code>__delitem__()</code></a> and <a class="reference internal" href="../reference/datamodel#object.__contains__" title="object.__contains__"><code>__contains__()</code></a>. For each of these methods, the key is the header name (treated case-insensitively), and the value is the first value associated with that header name. Setting a header deletes any existing values for that header, then adds a new value at the end of the wrapped header list. Headers’ existing order is generally maintained, with new headers added to the end of the wrapped list.</p> <p>Unlike a dictionary, <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code>Headers</code></a> objects do not raise an error when you try to get or delete a key that isn’t in the wrapped header list. Getting a nonexistent header just returns <code>None</code>, and deleting a nonexistent header does nothing.</p> <p><a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code>Headers</code></a> objects also support <code>keys()</code>, <code>values()</code>, and <code>items()</code> methods. The lists returned by <code>keys()</code> and <code>items()</code> can include the same key more than once if there is a multi-valued header. The <code>len()</code> of a <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code>Headers</code></a> object is the same as the length of its <code>items()</code>, which is the same as the length of the wrapped header list. In fact, the <code>items()</code> method just returns a copy of the wrapped header list.</p> <p>Calling <code>bytes()</code> on a <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code>Headers</code></a> object returns a formatted bytestring suitable for transmission as HTTP response headers. Each header is placed on a line with its value, separated by a colon and a space. Each line is terminated by a carriage return and line feed, and the bytestring is terminated with a blank line.</p> <p>In addition to their mapping interface and formatting features, <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code>Headers</code></a> objects also have the following methods for querying and adding multi-valued headers, and for adding headers with MIME parameters:</p> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.headers.Headers.get_all">
+<code>get_all(name)</code> </dt> <dd>
+<p>Return a list of all the values for the named header.</p> <p>The returned list will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.headers.Headers.add_header">
+<code>add_header(name, value, **_params)</code> </dt> <dd>
+<p>Add a (possibly multi-valued) header, with optional MIME parameters specified via keyword arguments.</p> <p><em>name</em> is the header field to add. Keyword arguments can be used to set MIME parameters for the header field. Each parameter must be a string or <code>None</code>. Underscores in parameter names are converted to dashes, since dashes are illegal in Python identifiers, but many MIME parameter names include dashes. If the parameter value is a string, it is added to the header value parameters in the form <code>name="value"</code>. If it is <code>None</code>, only the parameter name is added. (This is used for MIME parameters without a value.) Example usage:</p> <pre data-language="python">h.add_header('content-disposition', 'attachment', filename='bud.gif')
+</pre> <p>The above will add a header that looks like this:</p> <pre data-language="python">Content-Disposition: attachment; filename="bud.gif"
+</pre> </dd>
+</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span><em>headers</em> parameter is optional.</p> </div> </dd>
+</dl> </section> <section id="module-wsgiref.simple_server"> <span id="wsgiref-simple-server-a-simple-wsgi-http-server"></span><h2>wsgiref.simple_server – a simple WSGI HTTP server</h2> <p>This module implements a simple HTTP server (based on <a class="reference internal" href="http.server#module-http.server" title="http.server: HTTP server and request handlers."><code>http.server</code></a>) that serves WSGI applications. Each server instance serves a single WSGI application on a given host and port. If you want to serve multiple applications on a single host and port, you should create a WSGI application that parses <code>PATH_INFO</code> to select which application to invoke for each request. (E.g., using the <code>shift_path_info()</code> function from <a class="reference internal" href="#module-wsgiref.util" title="wsgiref.util: WSGI environment utilities."><code>wsgiref.util</code></a>.)</p> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.simple_server.make_server">
+<code>wsgiref.simple_server.make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)</code> </dt> <dd>
+<p>Create a new WSGI server listening on <em>host</em> and <em>port</em>, accepting connections for <em>app</em>. The return value is an instance of the supplied <em>server_class</em>, and will process requests using the specified <em>handler_class</em>. <em>app</em> must be a WSGI application object, as defined by <span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>.</p> <p>Example usage:</p> <pre data-language="python">from wsgiref.simple_server import make_server, demo_app
+
+with make_server('', 8000, demo_app) as httpd:
+ print("Serving HTTP on port 8000...")
+
+ # Respond to requests until process is killed
+ httpd.serve_forever()
+
+ # Alternative: serve one request, then exit
+ httpd.handle_request()
+</pre> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.simple_server.demo_app">
+<code>wsgiref.simple_server.demo_app(environ, start_response)</code> </dt> <dd>
+<p>This function is a small but complete WSGI application that returns a text page containing the message “Hello world!” and a list of the key/value pairs provided in the <em>environ</em> parameter. It’s useful for verifying that a WSGI server (such as <a class="reference internal" href="#module-wsgiref.simple_server" title="wsgiref.simple_server: A simple WSGI HTTP server."><code>wsgiref.simple_server</code></a>) is able to run a simple WSGI application correctly.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.simple_server.WSGIServer">
+<code>class wsgiref.simple_server.WSGIServer(server_address, RequestHandlerClass)</code> </dt> <dd>
+<p>Create a <a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code>WSGIServer</code></a> instance. <em>server_address</em> should be a <code>(host,port)</code> tuple, and <em>RequestHandlerClass</em> should be the subclass of <a class="reference internal" href="http.server#http.server.BaseHTTPRequestHandler" title="http.server.BaseHTTPRequestHandler"><code>http.server.BaseHTTPRequestHandler</code></a> that will be used to process requests.</p> <p>You do not normally need to call this constructor, as the <a class="reference internal" href="#wsgiref.simple_server.make_server" title="wsgiref.simple_server.make_server"><code>make_server()</code></a> function can handle all the details for you.</p> <p><a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code>WSGIServer</code></a> is a subclass of <a class="reference internal" href="http.server#http.server.HTTPServer" title="http.server.HTTPServer"><code>http.server.HTTPServer</code></a>, so all of its methods (such as <code>serve_forever()</code> and <code>handle_request()</code>) are available. <a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code>WSGIServer</code></a> also provides these WSGI-specific methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.simple_server.WSGIServer.set_app">
+<code>set_app(application)</code> </dt> <dd>
+<p>Sets the callable <em>application</em> as the WSGI application that will receive requests.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.simple_server.WSGIServer.get_app">
+<code>get_app()</code> </dt> <dd>
+<p>Returns the currently set application callable.</p> </dd>
+</dl> <p>Normally, however, you do not need to use these additional methods, as <a class="reference internal" href="#wsgiref.simple_server.WSGIServer.set_app" title="wsgiref.simple_server.WSGIServer.set_app"><code>set_app()</code></a> is normally called by <a class="reference internal" href="#wsgiref.simple_server.make_server" title="wsgiref.simple_server.make_server"><code>make_server()</code></a>, and the <a class="reference internal" href="#wsgiref.simple_server.WSGIServer.get_app" title="wsgiref.simple_server.WSGIServer.get_app"><code>get_app()</code></a> exists mainly for the benefit of request handler instances.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.simple_server.WSGIRequestHandler">
+<code>class wsgiref.simple_server.WSGIRequestHandler(request, client_address, server)</code> </dt> <dd>
+<p>Create an HTTP handler for the given <em>request</em> (i.e. a socket), <em>client_address</em> (a <code>(host,port)</code> tuple), and <em>server</em> (<a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code>WSGIServer</code></a> instance).</p> <p>You do not need to create instances of this class directly; they are automatically created as needed by <a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code>WSGIServer</code></a> objects. You can, however, subclass this class and supply it as a <em>handler_class</em> to the <a class="reference internal" href="#wsgiref.simple_server.make_server" title="wsgiref.simple_server.make_server"><code>make_server()</code></a> function. Some possibly relevant methods for overriding in subclasses:</p> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.simple_server.WSGIRequestHandler.get_environ">
+<code>get_environ()</code> </dt> <dd>
+<p>Return a <a class="reference internal" href="#wsgiref.types.WSGIEnvironment" title="wsgiref.types.WSGIEnvironment"><code>WSGIEnvironment</code></a> dictionary for a request. The default implementation copies the contents of the <a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code>WSGIServer</code></a> object’s <code>base_environ</code> dictionary attribute and then adds various headers derived from the HTTP request. Each call to this method should return a new dictionary containing all of the relevant CGI environment variables as specified in <span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.simple_server.WSGIRequestHandler.get_stderr">
+<code>get_stderr()</code> </dt> <dd>
+<p>Return the object that should be used as the <code>wsgi.errors</code> stream. The default implementation just returns <code>sys.stderr</code>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.simple_server.WSGIRequestHandler.handle">
+<code>handle()</code> </dt> <dd>
+<p>Process the HTTP request. The default implementation creates a handler instance using a <a class="reference internal" href="#module-wsgiref.handlers" title="wsgiref.handlers: WSGI server/gateway base classes."><code>wsgiref.handlers</code></a> class to implement the actual WSGI application interface.</p> </dd>
+</dl> </dd>
+</dl> </section> <section id="module-wsgiref.validate"> <span id="wsgiref-validate-wsgi-conformance-checker"></span><h2>wsgiref.validate — WSGI conformance checker</h2> <p>When creating new WSGI application objects, frameworks, servers, or middleware, it can be useful to validate the new code’s conformance using <a class="reference internal" href="#module-wsgiref.validate" title="wsgiref.validate: WSGI conformance checker."><code>wsgiref.validate</code></a>. This module provides a function that creates WSGI application objects that validate communications between a WSGI server or gateway and a WSGI application object, to check both sides for protocol conformance.</p> <p>Note that this utility does not guarantee complete <span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a> compliance; an absence of errors from this module does not necessarily mean that errors do not exist. However, if this module does produce an error, then it is virtually certain that either the server or application is not 100% compliant.</p> <p>This module is based on the <code>paste.lint</code> module from Ian Bicking’s “Python Paste” library.</p> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.validate.validator">
+<code>wsgiref.validate.validator(application)</code> </dt> <dd>
+<p>Wrap <em>application</em> and return a new WSGI application object. The returned application will forward all requests to the original <em>application</em>, and will check that both the <em>application</em> and the server invoking it are conforming to the WSGI specification and to <span class="target" id="index-10"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2616.html"><strong>RFC 2616</strong></a>.</p> <p>Any detected nonconformance results in an <a class="reference internal" href="exceptions#AssertionError" title="AssertionError"><code>AssertionError</code></a> being raised; note, however, that how these errors are handled is server-dependent. For example, <a class="reference internal" href="#module-wsgiref.simple_server" title="wsgiref.simple_server: A simple WSGI HTTP server."><code>wsgiref.simple_server</code></a> and other servers based on <a class="reference internal" href="#module-wsgiref.handlers" title="wsgiref.handlers: WSGI server/gateway base classes."><code>wsgiref.handlers</code></a> (that don’t override the error handling methods to do something else) will simply output a message that an error has occurred, and dump the traceback to <code>sys.stderr</code> or some other error stream.</p> <p>This wrapper may also generate output using the <a class="reference internal" href="warnings#module-warnings" title="warnings: Issue warning messages and control their disposition."><code>warnings</code></a> module to indicate behaviors that are questionable but which may not actually be prohibited by <span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>. Unless they are suppressed using Python command-line options or the <a class="reference internal" href="warnings#module-warnings" title="warnings: Issue warning messages and control their disposition."><code>warnings</code></a> API, any such warnings will be written to <code>sys.stderr</code> (<em>not</em> <code>wsgi.errors</code>, unless they happen to be the same object).</p> <p>Example usage:</p> <pre data-language="python">from wsgiref.validate import validator
+from wsgiref.simple_server import make_server
+
+# Our callable object which is intentionally not compliant to the
+# standard, so the validator is going to break
+def simple_app(environ, start_response):
+ status = '200 OK' # HTTP Status
+ headers = [('Content-type', 'text/plain')] # HTTP Headers
+ start_response(status, headers)
+
+ # This is going to break because we need to return a list, and
+ # the validator is going to inform us
+ return b"Hello World"
+
+# This is the application wrapped in a validator
+validator_app = validator(simple_app)
+
+with make_server('', 8000, validator_app) as httpd:
+ print("Listening on port 8000....")
+ httpd.serve_forever()
+</pre> </dd>
+</dl> </section> <section id="module-wsgiref.handlers"> <span id="wsgiref-handlers-server-gateway-base-classes"></span><h2>wsgiref.handlers – server/gateway base classes</h2> <p>This module provides base handler classes for implementing WSGI servers and gateways. These base classes handle most of the work of communicating with a WSGI application, as long as they are given a CGI-like environment, along with input, output, and error streams.</p> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.handlers.CGIHandler">
+<code>class wsgiref.handlers.CGIHandler</code> </dt> <dd>
+<p>CGI-based invocation via <code>sys.stdin</code>, <code>sys.stdout</code>, <code>sys.stderr</code> and <code>os.environ</code>. This is useful when you have a WSGI application and want to run it as a CGI script. Simply invoke <code>CGIHandler().run(app)</code>, where <code>app</code> is the WSGI application object you wish to invoke.</p> <p>This class is a subclass of <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code>BaseCGIHandler</code></a> that sets <code>wsgi.run_once</code> to true, <code>wsgi.multithread</code> to false, and <code>wsgi.multiprocess</code> to true, and always uses <a class="reference internal" href="sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a> and <a class="reference internal" href="os#module-os" title="os: Miscellaneous operating system interfaces."><code>os</code></a> to obtain the necessary CGI streams and environment.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.handlers.IISCGIHandler">
+<code>class wsgiref.handlers.IISCGIHandler</code> </dt> <dd>
+<p>A specialized alternative to <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code>CGIHandler</code></a>, for use when deploying on Microsoft’s IIS web server, without having set the config allowPathInfo option (IIS&gt;=7) or metabase allowPathInfoForScriptMappings (IIS&lt;7).</p> <p>By default, IIS gives a <code>PATH_INFO</code> that duplicates the <code>SCRIPT_NAME</code> at the front, causing problems for WSGI applications that wish to implement routing. This handler strips any such duplicated path.</p> <p>IIS can be configured to pass the correct <code>PATH_INFO</code>, but this causes another bug where <code>PATH_TRANSLATED</code> is wrong. Luckily this variable is rarely used and is not guaranteed by WSGI. On IIS&lt;7, though, the setting can only be made on a vhost level, affecting all other script mappings, many of which break when exposed to the <code>PATH_TRANSLATED</code> bug. For this reason IIS&lt;7 is almost never deployed with the fix (Even IIS7 rarely uses it because there is still no UI for it.).</p> <p>There is no way for CGI code to tell whether the option was set, so a separate handler class is provided. It is used in the same way as <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code>CGIHandler</code></a>, i.e., by calling <code>IISCGIHandler().run(app)</code>, where <code>app</code> is the WSGI application object you wish to invoke.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseCGIHandler">
+<code>class wsgiref.handlers.BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)</code> </dt> <dd>
+<p>Similar to <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code>CGIHandler</code></a>, but instead of using the <a class="reference internal" href="sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a> and <a class="reference internal" href="os#module-os" title="os: Miscellaneous operating system interfaces."><code>os</code></a> modules, the CGI environment and I/O streams are specified explicitly. The <em>multithread</em> and <em>multiprocess</em> values are used to set the <code>wsgi.multithread</code> and <code>wsgi.multiprocess</code> flags for any applications run by the handler instance.</p> <p>This class is a subclass of <a class="reference internal" href="#wsgiref.handlers.SimpleHandler" title="wsgiref.handlers.SimpleHandler"><code>SimpleHandler</code></a> intended for use with software other than HTTP “origin servers”. If you are writing a gateway protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a <code>Status:</code> header to send an HTTP status, you probably want to subclass this instead of <a class="reference internal" href="#wsgiref.handlers.SimpleHandler" title="wsgiref.handlers.SimpleHandler"><code>SimpleHandler</code></a>.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.handlers.SimpleHandler">
+<code>class wsgiref.handlers.SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)</code> </dt> <dd>
+<p>Similar to <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code>BaseCGIHandler</code></a>, but designed for use with HTTP origin servers. If you are writing an HTTP server implementation, you will probably want to subclass this instead of <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code>BaseCGIHandler</code></a>.</p> <p>This class is a subclass of <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a>. It overrides the <code>__init__()</code>, <a class="reference internal" href="#wsgiref.handlers.BaseHandler.get_stdin" title="wsgiref.handlers.BaseHandler.get_stdin"><code>get_stdin()</code></a>, <a class="reference internal" href="#wsgiref.handlers.BaseHandler.get_stderr" title="wsgiref.handlers.BaseHandler.get_stderr"><code>get_stderr()</code></a>, <a class="reference internal" href="#wsgiref.handlers.BaseHandler.add_cgi_vars" title="wsgiref.handlers.BaseHandler.add_cgi_vars"><code>add_cgi_vars()</code></a>, <a class="reference internal" href="#wsgiref.handlers.BaseHandler._write" title="wsgiref.handlers.BaseHandler._write"><code>_write()</code></a>, and <a class="reference internal" href="#wsgiref.handlers.BaseHandler._flush" title="wsgiref.handlers.BaseHandler._flush"><code>_flush()</code></a> methods to support explicitly setting the environment and streams via the constructor. The supplied environment and streams are stored in the <code>stdin</code>, <code>stdout</code>, <code>stderr</code>, and <code>environ</code> attributes.</p> <p>The <a class="reference internal" href="io#io.BufferedIOBase.write" title="io.BufferedIOBase.write"><code>write()</code></a> method of <em>stdout</em> should write each chunk in full, like <a class="reference internal" href="io#io.BufferedIOBase" title="io.BufferedIOBase"><code>io.BufferedIOBase</code></a>.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler">
+<code>class wsgiref.handlers.BaseHandler</code> </dt> <dd>
+<p>This is an abstract base class for running WSGI applications. Each instance will handle a single HTTP request, although in principle you could create a subclass that was reusable for multiple requests.</p> <p><a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a> instances have only one method intended for external use:</p> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.run">
+<code>run(app)</code> </dt> <dd>
+<p>Run the specified WSGI application, <em>app</em>.</p> </dd>
+</dl> <p>All of the other <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a> methods are invoked by this method in the process of running the application, and thus exist primarily to allow customizing the process.</p> <p>The following methods MUST be overridden in a subclass:</p> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler._write">
+<code>_write(data)</code> </dt> <dd>
+<p>Buffer the bytes <em>data</em> for transmission to the client. It’s okay if this method actually transmits the data; <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a> just separates write and flush operations for greater efficiency when the underlying system actually has such a distinction.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler._flush">
+<code>_flush()</code> </dt> <dd>
+<p>Force buffered data to be transmitted to the client. It’s okay if this method is a no-op (i.e., if <a class="reference internal" href="#wsgiref.handlers.BaseHandler._write" title="wsgiref.handlers.BaseHandler._write"><code>_write()</code></a> actually sends the data).</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.get_stdin">
+<code>get_stdin()</code> </dt> <dd>
+<p>Return an object compatible with <a class="reference internal" href="#wsgiref.types.InputStream" title="wsgiref.types.InputStream"><code>InputStream</code></a> suitable for use as the <code>wsgi.input</code> of the request currently being processed.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.get_stderr">
+<code>get_stderr()</code> </dt> <dd>
+<p>Return an object compatible with <a class="reference internal" href="#wsgiref.types.ErrorStream" title="wsgiref.types.ErrorStream"><code>ErrorStream</code></a> suitable for use as the <code>wsgi.errors</code> of the request currently being processed.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.add_cgi_vars">
+<code>add_cgi_vars()</code> </dt> <dd>
+<p>Insert CGI variables for the current request into the <code>environ</code> attribute.</p> </dd>
+</dl> <p>Here are some other methods and attributes you may wish to override. This list is only a summary, however, and does not include every method that can be overridden. You should consult the docstrings and source code for additional information before attempting to create a customized <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a> subclass.</p> <p>Attributes and methods for customizing the WSGI environment:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.wsgi_multithread">
+<code>wsgi_multithread</code> </dt> <dd>
+<p>The value to be used for the <code>wsgi.multithread</code> environment variable. It defaults to true in <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a>, but may have a different default (or be set by the constructor) in the other subclasses.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.wsgi_multiprocess">
+<code>wsgi_multiprocess</code> </dt> <dd>
+<p>The value to be used for the <code>wsgi.multiprocess</code> environment variable. It defaults to true in <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a>, but may have a different default (or be set by the constructor) in the other subclasses.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.wsgi_run_once">
+<code>wsgi_run_once</code> </dt> <dd>
+<p>The value to be used for the <code>wsgi.run_once</code> environment variable. It defaults to false in <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a>, but <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code>CGIHandler</code></a> sets it to true by default.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.os_environ">
+<code>os_environ</code> </dt> <dd>
+<p>The default environment variables to be included in every request’s WSGI environment. By default, this is a copy of <code>os.environ</code> at the time that <a class="reference internal" href="#module-wsgiref.handlers" title="wsgiref.handlers: WSGI server/gateway base classes."><code>wsgiref.handlers</code></a> was imported, but subclasses can either create their own at the class or instance level. Note that the dictionary should be considered read-only, since the default value is shared between multiple classes and instances.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.server_software">
+<code>server_software</code> </dt> <dd>
+<p>If the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.origin_server" title="wsgiref.handlers.BaseHandler.origin_server"><code>origin_server</code></a> attribute is set, this attribute’s value is used to set the default <code>SERVER_SOFTWARE</code> WSGI environment variable, and also to set a default <code>Server:</code> header in HTTP responses. It is ignored for handlers (such as <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code>BaseCGIHandler</code></a> and <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code>CGIHandler</code></a>) that are not HTTP origin servers.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>The term “Python” is replaced with implementation specific term like “CPython”, “Jython” etc.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.get_scheme">
+<code>get_scheme()</code> </dt> <dd>
+<p>Return the URL scheme being used for the current request. The default implementation uses the <code>guess_scheme()</code> function from <a class="reference internal" href="#module-wsgiref.util" title="wsgiref.util: WSGI environment utilities."><code>wsgiref.util</code></a> to guess whether the scheme should be “http” or “https”, based on the current request’s <code>environ</code> variables.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.setup_environ">
+<code>setup_environ()</code> </dt> <dd>
+<p>Set the <code>environ</code> attribute to a fully populated WSGI environment. The default implementation uses all of the above methods and attributes, plus the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.get_stdin" title="wsgiref.handlers.BaseHandler.get_stdin"><code>get_stdin()</code></a>, <a class="reference internal" href="#wsgiref.handlers.BaseHandler.get_stderr" title="wsgiref.handlers.BaseHandler.get_stderr"><code>get_stderr()</code></a>, and <a class="reference internal" href="#wsgiref.handlers.BaseHandler.add_cgi_vars" title="wsgiref.handlers.BaseHandler.add_cgi_vars"><code>add_cgi_vars()</code></a> methods and the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.wsgi_file_wrapper" title="wsgiref.handlers.BaseHandler.wsgi_file_wrapper"><code>wsgi_file_wrapper</code></a> attribute. It also inserts a <code>SERVER_SOFTWARE</code> key if not present, as long as the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.origin_server" title="wsgiref.handlers.BaseHandler.origin_server"><code>origin_server</code></a> attribute is a true value and the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.server_software" title="wsgiref.handlers.BaseHandler.server_software"><code>server_software</code></a> attribute is set.</p> </dd>
+</dl> <p>Methods and attributes for customizing exception handling:</p> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.log_exception">
+<code>log_exception(exc_info)</code> </dt> <dd>
+<p>Log the <em>exc_info</em> tuple in the server log. <em>exc_info</em> is a <code>(type, value,
+traceback)</code> tuple. The default implementation simply writes the traceback to the request’s <code>wsgi.errors</code> stream and flushes it. Subclasses can override this method to change the format or retarget the output, mail the traceback to an administrator, or whatever other action may be deemed suitable.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.traceback_limit">
+<code>traceback_limit</code> </dt> <dd>
+<p>The maximum number of frames to include in tracebacks output by the default <a class="reference internal" href="#wsgiref.handlers.BaseHandler.log_exception" title="wsgiref.handlers.BaseHandler.log_exception"><code>log_exception()</code></a> method. If <code>None</code>, all frames are included.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.error_output">
+<code>error_output(environ, start_response)</code> </dt> <dd>
+<p>This method is a WSGI application to generate an error page for the user. It is only invoked if an error occurs before headers are sent to the client.</p> <p>This method can access the current error using <code>sys.exception()</code>, and should pass that information to <em>start_response</em> when calling it (as described in the “Error Handling” section of <span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>).</p> <p>The default implementation just uses the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.error_status" title="wsgiref.handlers.BaseHandler.error_status"><code>error_status</code></a>, <a class="reference internal" href="#wsgiref.handlers.BaseHandler.error_headers" title="wsgiref.handlers.BaseHandler.error_headers"><code>error_headers</code></a>, and <a class="reference internal" href="#wsgiref.handlers.BaseHandler.error_body" title="wsgiref.handlers.BaseHandler.error_body"><code>error_body</code></a> attributes to generate an output page. Subclasses can override this to produce more dynamic error output.</p> <p>Note, however, that it’s not recommended from a security perspective to spit out diagnostics to any old user; ideally, you should have to do something special to enable diagnostic output, which is why the default implementation doesn’t include any.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.error_status">
+<code>error_status</code> </dt> <dd>
+<p>The HTTP status used for error responses. This should be a status string as defined in <span class="target" id="index-13"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>; it defaults to a 500 code and message.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.error_headers">
+<code>error_headers</code> </dt> <dd>
+<p>The HTTP headers used for error responses. This should be a list of WSGI response headers (<code>(name, value)</code> tuples), as described in <span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>. The default list just sets the content type to <code>text/plain</code>.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.error_body">
+<code>error_body</code> </dt> <dd>
+<p>The error response body. This should be an HTTP response body bytestring. It defaults to the plain text, “A server error occurred. Please contact the administrator.”</p> </dd>
+</dl> <p>Methods and attributes for <span class="target" id="index-15"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>’s “Optional Platform-Specific File Handling” feature:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.wsgi_file_wrapper">
+<code>wsgi_file_wrapper</code> </dt> <dd>
+<p>A <code>wsgi.file_wrapper</code> factory, compatible with <a class="reference internal" href="#wsgiref.types.FileWrapper" title="wsgiref.types.FileWrapper"><code>wsgiref.types.FileWrapper</code></a>, or <code>None</code>. The default value of this attribute is the <a class="reference internal" href="#wsgiref.util.FileWrapper" title="wsgiref.util.FileWrapper"><code>wsgiref.util.FileWrapper</code></a> class.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.sendfile">
+<code>sendfile()</code> </dt> <dd>
+<p>Override to implement platform-specific file transmission. This method is called only if the application’s return value is an instance of the class specified by the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.wsgi_file_wrapper" title="wsgiref.handlers.BaseHandler.wsgi_file_wrapper"><code>wsgi_file_wrapper</code></a> attribute. It should return a true value if it was able to successfully transmit the file, so that the default transmission code will not be executed. The default implementation of this method just returns a false value.</p> </dd>
+</dl> <p>Miscellaneous methods and attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.origin_server">
+<code>origin_server</code> </dt> <dd>
+<p>This attribute should be set to a true value if the handler’s <a class="reference internal" href="#wsgiref.handlers.BaseHandler._write" title="wsgiref.handlers.BaseHandler._write"><code>_write()</code></a> and <a class="reference internal" href="#wsgiref.handlers.BaseHandler._flush" title="wsgiref.handlers.BaseHandler._flush"><code>_flush()</code></a> are being used to communicate directly to the client, rather than via a CGI-like gateway protocol that wants the HTTP status in a special <code>Status:</code> header.</p> <p>This attribute’s default value is true in <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code>BaseHandler</code></a>, but false in <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code>BaseCGIHandler</code></a> and <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code>CGIHandler</code></a>.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="wsgiref.handlers.BaseHandler.http_version">
+<code>http_version</code> </dt> <dd>
+<p>If <a class="reference internal" href="#wsgiref.handlers.BaseHandler.origin_server" title="wsgiref.handlers.BaseHandler.origin_server"><code>origin_server</code></a> is true, this string attribute is used to set the HTTP version of the response set to the client. It defaults to <code>"1.0"</code>.</p> </dd>
+</dl> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="wsgiref.handlers.read_environ">
+<code>wsgiref.handlers.read_environ()</code> </dt> <dd>
+<p>Transcode CGI variables from <code>os.environ</code> to <span class="target" id="index-16"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a> “bytes in unicode” strings, returning a new dictionary. This function is used by <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code>CGIHandler</code></a> and <a class="reference internal" href="#wsgiref.handlers.IISCGIHandler" title="wsgiref.handlers.IISCGIHandler"><code>IISCGIHandler</code></a> in place of directly using <code>os.environ</code>, which is not necessarily WSGI-compliant on all platforms and web servers using Python 3 – specifically, ones where the OS’s actual environment is Unicode (i.e. Windows), or ones where the environment is bytes, but the system encoding used by Python to decode it is anything other than ISO-8859-1 (e.g. Unix systems using UTF-8).</p> <p>If you are implementing a CGI-based handler of your own, you probably want to use this routine instead of just copying values out of <code>os.environ</code> directly.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> </section> <section id="module-wsgiref.types"> <span id="wsgiref-types-wsgi-types-for-static-type-checking"></span><h2>wsgiref.types – WSGI types for static type checking</h2> <p>This module provides various types for static type checking as described in <span class="target" id="index-17"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.types.StartResponse">
+<code>class wsgiref.types.StartResponse</code> </dt> <dd>
+<p>A <a class="reference internal" href="typing#typing.Protocol" title="typing.Protocol"><code>typing.Protocol</code></a> describing <a class="reference external" href="https://peps.python.org/pep-3333/#the-start-response-callable">start_response()</a> callables (<span class="target" id="index-18"></span><a class="pep reference external" href="https://peps.python.org/pep-3333/"><strong>PEP 3333</strong></a>).</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="wsgiref.types.WSGIEnvironment">
+<code>wsgiref.types.WSGIEnvironment</code> </dt> <dd>
+<p>A type alias describing a WSGI environment dictionary.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="wsgiref.types.WSGIApplication">
+<code>wsgiref.types.WSGIApplication</code> </dt> <dd>
+<p>A type alias describing a WSGI application callable.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.types.InputStream">
+<code>class wsgiref.types.InputStream</code> </dt> <dd>
+<p>A <a class="reference internal" href="typing#typing.Protocol" title="typing.Protocol"><code>typing.Protocol</code></a> describing a <a class="reference external" href="https://peps.python.org/pep-3333/#input-and-error-streams">WSGI Input Stream</a>.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.types.ErrorStream">
+<code>class wsgiref.types.ErrorStream</code> </dt> <dd>
+<p>A <a class="reference internal" href="typing#typing.Protocol" title="typing.Protocol"><code>typing.Protocol</code></a> describing a <a class="reference external" href="https://peps.python.org/pep-3333/#input-and-error-streams">WSGI Error Stream</a>.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="wsgiref.types.FileWrapper">
+<code>class wsgiref.types.FileWrapper</code> </dt> <dd>
+<p>A <a class="reference internal" href="typing#typing.Protocol" title="typing.Protocol"><code>typing.Protocol</code></a> describing a <a class="reference external" href="https://peps.python.org/pep-3333/#optional-platform-specific-file-handling">file wrapper</a>. See <a class="reference internal" href="#wsgiref.util.FileWrapper" title="wsgiref.util.FileWrapper"><code>wsgiref.util.FileWrapper</code></a> for a concrete implementation of this protocol.</p> </dd>
+</dl> </section> <section id="examples"> <h2>Examples</h2> <p>This is a working “Hello World” WSGI application:</p> <pre data-language="python">"""
+Every WSGI application must have an application object - a callable
+object that accepts two arguments. For that purpose, we're going to
+use a function (note that you're not limited to a function, you can
+use a class for example). The first argument passed to the function
+is a dictionary containing CGI-style environment variables and the
+second variable is the callable object.
+"""
+from wsgiref.simple_server import make_server
+
+
+def hello_world_app(environ, start_response):
+ status = "200 OK" # HTTP Status
+ headers = [("Content-type", "text/plain; charset=utf-8")] # HTTP Headers
+ start_response(status, headers)
+
+ # The returned object is going to be printed
+ return [b"Hello World"]
+
+with make_server("", 8000, hello_world_app) as httpd:
+ print("Serving on port 8000...")
+
+ # Serve until process is killed
+ httpd.serve_forever()
+</pre> <p>Example of a WSGI application serving the current directory, accept optional directory and port number (default: 8000) on the command line:</p> <pre data-language="python">"""
+Small wsgiref based web server. Takes a path to serve from and an
+optional port number (defaults to 8000), then tries to serve files.
+MIME types are guessed from the file names, 404 errors are raised
+if the file is not found.
+"""
+import mimetypes
+import os
+import sys
+from wsgiref import simple_server, util
+
+
+def app(environ, respond):
+ # Get the file name and MIME type
+ fn = os.path.join(path, environ["PATH_INFO"][1:])
+ if "." not in fn.split(os.path.sep)[-1]:
+ fn = os.path.join(fn, "index.html")
+ mime_type = mimetypes.guess_type(fn)[0]
+
+ # Return 200 OK if file exists, otherwise 404 Not Found
+ if os.path.exists(fn):
+ respond("200 OK", [("Content-Type", mime_type)])
+ return util.FileWrapper(open(fn, "rb"))
+ else:
+ respond("404 Not Found", [("Content-Type", "text/plain")])
+ return [b"not found"]
+
+
+if __name__ == "__main__":
+ # Get the path and port from command-line arguments
+ path = sys.argv[1] if len(sys.argv) &gt; 1 else os.getcwd()
+ port = int(sys.argv[2]) if len(sys.argv) &gt; 2 else 8000
+
+ # Make and start the server until control-c
+ httpd = simple_server.make_server("", port, app)
+ print(f"Serving {path} on port {port}, control-C to stop")
+ try:
+ httpd.serve_forever()
+ except KeyboardInterrupt:
+ print("Shutting down.")
+ httpd.server_close()
+</pre> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/wsgiref.html" class="_attribution-link">https://docs.python.org/3.12/library/wsgiref.html</a>
+ </p>
+</div>