Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`wsgiref` --- WSGI Utilities and Reference Implementation |
| 2 | ============================================================== |
| 3 | |
| 4 | .. module:: wsgiref |
| 5 | :synopsis: WSGI Utilities and Reference Implementation. |
| 6 | .. moduleauthor:: Phillip J. Eby <pje@telecommunity.com> |
| 7 | .. sectionauthor:: Phillip J. Eby <pje@telecommunity.com> |
| 8 | |
| 9 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 10 | The Web Server Gateway Interface (WSGI) is a standard interface between web |
| 11 | server software and web applications written in Python. Having a standard |
| 12 | interface makes it easy to use an application that supports WSGI with a number |
| 13 | of different web servers. |
| 14 | |
| 15 | Only authors of web servers and programming frameworks need to know every detail |
| 16 | and corner case of the WSGI design. You don't need to understand every detail |
| 17 | of WSGI just to install a WSGI application or to write a web application using |
| 18 | an existing framework. |
| 19 | |
| 20 | :mod:`wsgiref` is a reference implementation of the WSGI specification that can |
| 21 | be used to add WSGI support to a web server or framework. It provides utilities |
| 22 | for manipulating WSGI environment variables and response headers, base classes |
| 23 | for implementing WSGI servers, a demo HTTP server that serves WSGI applications, |
| 24 | and a validation tool that checks WSGI servers and applications for conformance |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 25 | to the WSGI specification (:pep:`3333`). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 26 | |
| 27 | See http://www.wsgi.org for more information about WSGI, and links to tutorials |
| 28 | and other resources. |
| 29 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 30 | .. XXX If you're just trying to write a web application... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 31 | |
| 32 | |
| 33 | :mod:`wsgiref.util` -- WSGI environment utilities |
| 34 | ------------------------------------------------- |
| 35 | |
| 36 | .. module:: wsgiref.util |
| 37 | :synopsis: WSGI environment utilities. |
| 38 | |
| 39 | |
| 40 | This module provides a variety of utility functions for working with WSGI |
| 41 | environments. A WSGI environment is a dictionary containing HTTP request |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 42 | variables as described in :pep:`3333`. All of the functions taking an *environ* |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 43 | parameter expect a WSGI-compliant dictionary to be supplied; please see |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 44 | :pep:`3333` for a detailed specification. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 45 | |
| 46 | |
| 47 | .. function:: guess_scheme(environ) |
| 48 | |
| 49 | Return a guess for whether ``wsgi.url_scheme`` should be "http" or "https", by |
| 50 | checking for a ``HTTPS`` environment variable in the *environ* dictionary. The |
| 51 | return value is a string. |
| 52 | |
| 53 | This function is useful when creating a gateway that wraps CGI or a CGI-like |
| 54 | protocol such as FastCGI. Typically, servers providing such protocols will |
| 55 | include a ``HTTPS`` variable with a value of "1" "yes", or "on" when a request |
| 56 | is received via SSL. So, this function returns "https" if such a value is |
| 57 | found, and "http" otherwise. |
| 58 | |
| 59 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 60 | .. function:: request_uri(environ, include_query=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 61 | |
| 62 | Return the full request URI, optionally including the query string, using the |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 63 | algorithm found in the "URL Reconstruction" section of :pep:`3333`. If |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 64 | *include_query* is false, the query string is not included in the resulting URI. |
| 65 | |
| 66 | |
| 67 | .. function:: application_uri(environ) |
| 68 | |
| 69 | Similar to :func:`request_uri`, except that the ``PATH_INFO`` and |
| 70 | ``QUERY_STRING`` variables are ignored. The result is the base URI of the |
| 71 | application object addressed by the request. |
| 72 | |
| 73 | |
| 74 | .. function:: shift_path_info(environ) |
| 75 | |
| 76 | Shift a single name from ``PATH_INFO`` to ``SCRIPT_NAME`` and return the name. |
| 77 | The *environ* dictionary is *modified* in-place; use a copy if you need to keep |
| 78 | the original ``PATH_INFO`` or ``SCRIPT_NAME`` intact. |
| 79 | |
| 80 | If there are no remaining path segments in ``PATH_INFO``, ``None`` is returned. |
| 81 | |
| 82 | Typically, this routine is used to process each portion of a request URI path, |
| 83 | for example to treat the path as a series of dictionary keys. This routine |
| 84 | modifies the passed-in environment to make it suitable for invoking another WSGI |
| 85 | application that is located at the target URI. For example, if there is a WSGI |
| 86 | application at ``/foo``, and the request URI path is ``/foo/bar/baz``, and the |
| 87 | WSGI application at ``/foo`` calls :func:`shift_path_info`, it will receive the |
| 88 | string "bar", and the environment will be updated to be suitable for passing to |
| 89 | a WSGI application at ``/foo/bar``. That is, ``SCRIPT_NAME`` will change from |
| 90 | ``/foo`` to ``/foo/bar``, and ``PATH_INFO`` will change from ``/bar/baz`` to |
| 91 | ``/baz``. |
| 92 | |
| 93 | When ``PATH_INFO`` is just a "/", this routine returns an empty string and |
| 94 | appends a trailing slash to ``SCRIPT_NAME``, even though empty path segments are |
| 95 | normally ignored, and ``SCRIPT_NAME`` doesn't normally end in a slash. This is |
| 96 | intentional behavior, to ensure that an application can tell the difference |
| 97 | between URIs ending in ``/x`` from ones ending in ``/x/`` when using this |
| 98 | routine to do object traversal. |
| 99 | |
| 100 | |
| 101 | .. function:: setup_testing_defaults(environ) |
| 102 | |
| 103 | Update *environ* with trivial defaults for testing purposes. |
| 104 | |
| 105 | This routine adds various parameters required for WSGI, including ``HTTP_HOST``, |
| 106 | ``SERVER_NAME``, ``SERVER_PORT``, ``REQUEST_METHOD``, ``SCRIPT_NAME``, |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 107 | ``PATH_INFO``, and all of the :pep:`3333`\ -defined ``wsgi.*`` variables. It |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 108 | only supplies default values, and does not replace any existing settings for |
| 109 | these variables. |
| 110 | |
| 111 | This routine is intended to make it easier for unit tests of WSGI servers and |
| 112 | applications to set up dummy environments. It should NOT be used by actual WSGI |
| 113 | servers or applications, since the data is fake! |
| 114 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 115 | Example usage:: |
| 116 | |
| 117 | from wsgiref.util import setup_testing_defaults |
| 118 | from wsgiref.simple_server import make_server |
| 119 | |
| 120 | # A relatively simple WSGI application. It's going to print out the |
| 121 | # environment dictionary after being updated by setup_testing_defaults |
| 122 | def simple_app(environ, start_response): |
| 123 | setup_testing_defaults(environ) |
| 124 | |
Antoine Pitrou | 38a66ad | 2009-01-03 18:41:49 +0000 | [diff] [blame] | 125 | status = b'200 OK' |
| 126 | headers = [(b'Content-type', b'text/plain; charset=utf-8')] |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 127 | |
| 128 | start_response(status, headers) |
| 129 | |
Antoine Pitrou | 38a66ad | 2009-01-03 18:41:49 +0000 | [diff] [blame] | 130 | ret = [("%s: %s\n" % (key, value)).encode("utf-8") |
| 131 | for key, value in environ.items()] |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 132 | return ret |
| 133 | |
| 134 | httpd = make_server('', 8000, simple_app) |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 135 | print("Serving on port 8000...") |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 136 | httpd.serve_forever() |
| 137 | |
| 138 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 139 | In addition to the environment functions above, the :mod:`wsgiref.util` module |
| 140 | also provides these miscellaneous utilities: |
| 141 | |
| 142 | |
| 143 | .. function:: is_hop_by_hop(header_name) |
| 144 | |
| 145 | Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header, as defined by |
| 146 | :rfc:`2616`. |
| 147 | |
| 148 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 149 | .. class:: FileWrapper(filelike, blksize=8192) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 150 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 151 | A wrapper to convert a file-like object to an :term:`iterator`. The resulting objects |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 152 | support both :meth:`__getitem__` and :meth:`__iter__` iteration styles, for |
| 153 | compatibility with Python 2.1 and Jython. As the object is iterated over, the |
| 154 | optional *blksize* parameter will be repeatedly passed to the *filelike* |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 155 | object's :meth:`read` method to obtain bytestrings to yield. When :meth:`read` |
| 156 | returns an empty bytestring, iteration is ended and is not resumable. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 157 | |
| 158 | If *filelike* has a :meth:`close` method, the returned object will also have a |
| 159 | :meth:`close` method, and it will invoke the *filelike* object's :meth:`close` |
| 160 | method when called. |
| 161 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 162 | Example usage:: |
| 163 | |
Antoine Pitrou | 38a66ad | 2009-01-03 18:41:49 +0000 | [diff] [blame] | 164 | from io import StringIO |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 165 | from wsgiref.util import FileWrapper |
| 166 | |
| 167 | # We're using a StringIO-buffer for as the file-like object |
| 168 | filelike = StringIO("This is an example file-like object"*10) |
| 169 | wrapper = FileWrapper(filelike, blksize=5) |
| 170 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 171 | for chunk in wrapper: |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 172 | print(chunk) |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 173 | |
| 174 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 175 | |
| 176 | :mod:`wsgiref.headers` -- WSGI response header tools |
| 177 | ---------------------------------------------------- |
| 178 | |
| 179 | .. module:: wsgiref.headers |
| 180 | :synopsis: WSGI response header tools. |
| 181 | |
| 182 | |
| 183 | This module provides a single class, :class:`Headers`, for convenient |
| 184 | manipulation of WSGI response headers using a mapping-like interface. |
| 185 | |
| 186 | |
| 187 | .. class:: Headers(headers) |
| 188 | |
| 189 | Create a mapping-like object wrapping *headers*, which must be a list of header |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 190 | name/value tuples as described in :pep:`3333`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 191 | |
| 192 | :class:`Headers` objects support typical mapping operations including |
| 193 | :meth:`__getitem__`, :meth:`get`, :meth:`__setitem__`, :meth:`setdefault`, |
Collin Winter | f6b8121 | 2007-09-10 00:03:41 +0000 | [diff] [blame] | 194 | :meth:`__delitem__` and :meth:`__contains__`. For each of |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 195 | these methods, the key is the header name (treated case-insensitively), and the |
| 196 | value is the first value associated with that header name. Setting a header |
| 197 | deletes any existing values for that header, then adds a new value at the end of |
| 198 | the wrapped header list. Headers' existing order is generally maintained, with |
| 199 | new headers added to the end of the wrapped list. |
| 200 | |
| 201 | Unlike a dictionary, :class:`Headers` objects do not raise an error when you try |
| 202 | to get or delete a key that isn't in the wrapped header list. Getting a |
| 203 | nonexistent header just returns ``None``, and deleting a nonexistent header does |
| 204 | nothing. |
| 205 | |
| 206 | :class:`Headers` objects also support :meth:`keys`, :meth:`values`, and |
| 207 | :meth:`items` methods. The lists returned by :meth:`keys` and :meth:`items` can |
| 208 | include the same key more than once if there is a multi-valued header. The |
| 209 | ``len()`` of a :class:`Headers` object is the same as the length of its |
| 210 | :meth:`items`, which is the same as the length of the wrapped header list. In |
| 211 | fact, the :meth:`items` method just returns a copy of the wrapped header list. |
| 212 | |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 213 | Calling ``bytes()`` on a :class:`Headers` object returns a formatted bytestring |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 214 | suitable for transmission as HTTP response headers. Each header is placed on a |
| 215 | line with its value, separated by a colon and a space. Each line is terminated |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 216 | by a carriage return and line feed, and the bytestring is terminated with a |
| 217 | blank line. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 218 | |
| 219 | In addition to their mapping interface and formatting features, :class:`Headers` |
| 220 | objects also have the following methods for querying and adding multi-valued |
| 221 | headers, and for adding headers with MIME parameters: |
| 222 | |
| 223 | |
| 224 | .. method:: Headers.get_all(name) |
| 225 | |
| 226 | Return a list of all the values for the named header. |
| 227 | |
| 228 | The returned list will be sorted in the order they appeared in the original |
| 229 | header list or were added to this instance, and may contain duplicates. Any |
| 230 | fields deleted and re-inserted are always appended to the header list. If no |
| 231 | fields exist with the given name, returns an empty list. |
| 232 | |
| 233 | |
| 234 | .. method:: Headers.add_header(name, value, **_params) |
| 235 | |
| 236 | Add a (possibly multi-valued) header, with optional MIME parameters specified |
| 237 | via keyword arguments. |
| 238 | |
| 239 | *name* is the header field to add. Keyword arguments can be used to set MIME |
| 240 | parameters for the header field. Each parameter must be a string or ``None``. |
| 241 | Underscores in parameter names are converted to dashes, since dashes are illegal |
| 242 | in Python identifiers, but many MIME parameter names include dashes. If the |
| 243 | parameter value is a string, it is added to the header value parameters in the |
| 244 | form ``name="value"``. If it is ``None``, only the parameter name is added. |
| 245 | (This is used for MIME parameters without a value.) Example usage:: |
| 246 | |
| 247 | h.add_header('content-disposition', 'attachment', filename='bud.gif') |
| 248 | |
| 249 | The above will add a header that looks like this:: |
| 250 | |
| 251 | Content-Disposition: attachment; filename="bud.gif" |
| 252 | |
| 253 | |
| 254 | :mod:`wsgiref.simple_server` -- a simple WSGI HTTP server |
| 255 | --------------------------------------------------------- |
| 256 | |
| 257 | .. module:: wsgiref.simple_server |
| 258 | :synopsis: A simple WSGI HTTP server. |
| 259 | |
| 260 | |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 261 | This module implements a simple HTTP server (based on :mod:`http.server`) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 262 | that serves WSGI applications. Each server instance serves a single WSGI |
| 263 | application on a given host and port. If you want to serve multiple |
| 264 | applications on a single host and port, you should create a WSGI application |
| 265 | that parses ``PATH_INFO`` to select which application to invoke for each |
| 266 | request. (E.g., using the :func:`shift_path_info` function from |
| 267 | :mod:`wsgiref.util`.) |
| 268 | |
| 269 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 270 | .. function:: make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 271 | |
| 272 | Create a new WSGI server listening on *host* and *port*, accepting connections |
| 273 | for *app*. The return value is an instance of the supplied *server_class*, and |
| 274 | will process requests using the specified *handler_class*. *app* must be a WSGI |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 275 | application object, as defined by :pep:`3333`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 276 | |
| 277 | Example usage:: |
| 278 | |
| 279 | from wsgiref.simple_server import make_server, demo_app |
| 280 | |
| 281 | httpd = make_server('', 8000, demo_app) |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 282 | print("Serving HTTP on port 8000...") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 283 | |
| 284 | # Respond to requests until process is killed |
| 285 | httpd.serve_forever() |
| 286 | |
| 287 | # Alternative: serve one request, then exit |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 288 | httpd.handle_request() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 289 | |
| 290 | |
| 291 | .. function:: demo_app(environ, start_response) |
| 292 | |
| 293 | This function is a small but complete WSGI application that returns a text page |
| 294 | containing the message "Hello world!" and a list of the key/value pairs provided |
| 295 | in the *environ* parameter. It's useful for verifying that a WSGI server (such |
| 296 | as :mod:`wsgiref.simple_server`) is able to run a simple WSGI application |
| 297 | correctly. |
| 298 | |
| 299 | |
| 300 | .. class:: WSGIServer(server_address, RequestHandlerClass) |
| 301 | |
| 302 | Create a :class:`WSGIServer` instance. *server_address* should be a |
| 303 | ``(host,port)`` tuple, and *RequestHandlerClass* should be the subclass of |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 304 | :class:`http.server.BaseHTTPRequestHandler` that will be used to process |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 305 | requests. |
| 306 | |
| 307 | You do not normally need to call this constructor, as the :func:`make_server` |
| 308 | function can handle all the details for you. |
| 309 | |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 310 | :class:`WSGIServer` is a subclass of :class:`http.server.HTTPServer`, so all |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 311 | of its methods (such as :meth:`serve_forever` and :meth:`handle_request`) are |
| 312 | available. :class:`WSGIServer` also provides these WSGI-specific methods: |
| 313 | |
| 314 | |
| 315 | .. method:: WSGIServer.set_app(application) |
| 316 | |
| 317 | Sets the callable *application* as the WSGI application that will receive |
| 318 | requests. |
| 319 | |
| 320 | |
| 321 | .. method:: WSGIServer.get_app() |
| 322 | |
| 323 | Returns the currently-set application callable. |
| 324 | |
| 325 | Normally, however, you do not need to use these additional methods, as |
| 326 | :meth:`set_app` is normally called by :func:`make_server`, and the |
| 327 | :meth:`get_app` exists mainly for the benefit of request handler instances. |
| 328 | |
| 329 | |
| 330 | .. class:: WSGIRequestHandler(request, client_address, server) |
| 331 | |
| 332 | Create an HTTP handler for the given *request* (i.e. a socket), *client_address* |
| 333 | (a ``(host,port)`` tuple), and *server* (:class:`WSGIServer` instance). |
| 334 | |
| 335 | You do not need to create instances of this class directly; they are |
| 336 | automatically created as needed by :class:`WSGIServer` objects. You can, |
| 337 | however, subclass this class and supply it as a *handler_class* to the |
| 338 | :func:`make_server` function. Some possibly relevant methods for overriding in |
| 339 | subclasses: |
| 340 | |
| 341 | |
| 342 | .. method:: WSGIRequestHandler.get_environ() |
| 343 | |
| 344 | Returns a dictionary containing the WSGI environment for a request. The default |
| 345 | implementation copies the contents of the :class:`WSGIServer` object's |
| 346 | :attr:`base_environ` dictionary attribute and then adds various headers derived |
| 347 | from the HTTP request. Each call to this method should return a new dictionary |
| 348 | containing all of the relevant CGI environment variables as specified in |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 349 | :pep:`3333`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 350 | |
| 351 | |
| 352 | .. method:: WSGIRequestHandler.get_stderr() |
| 353 | |
| 354 | Return the object that should be used as the ``wsgi.errors`` stream. The default |
| 355 | implementation just returns ``sys.stderr``. |
| 356 | |
| 357 | |
| 358 | .. method:: WSGIRequestHandler.handle() |
| 359 | |
| 360 | Process the HTTP request. The default implementation creates a handler instance |
| 361 | using a :mod:`wsgiref.handlers` class to implement the actual WSGI application |
| 362 | interface. |
| 363 | |
| 364 | |
| 365 | :mod:`wsgiref.validate` --- WSGI conformance checker |
| 366 | ---------------------------------------------------- |
| 367 | |
| 368 | .. module:: wsgiref.validate |
| 369 | :synopsis: WSGI conformance checker. |
| 370 | |
| 371 | |
| 372 | When creating new WSGI application objects, frameworks, servers, or middleware, |
| 373 | it can be useful to validate the new code's conformance using |
| 374 | :mod:`wsgiref.validate`. This module provides a function that creates WSGI |
| 375 | application objects that validate communications between a WSGI server or |
| 376 | gateway and a WSGI application object, to check both sides for protocol |
| 377 | conformance. |
| 378 | |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 379 | Note that this utility does not guarantee complete :pep:`3333` compliance; an |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 380 | absence of errors from this module does not necessarily mean that errors do not |
| 381 | exist. However, if this module does produce an error, then it is virtually |
| 382 | certain that either the server or application is not 100% compliant. |
| 383 | |
| 384 | This module is based on the :mod:`paste.lint` module from Ian Bicking's "Python |
| 385 | Paste" library. |
| 386 | |
| 387 | |
| 388 | .. function:: validator(application) |
| 389 | |
| 390 | Wrap *application* and return a new WSGI application object. The returned |
| 391 | application will forward all requests to the original *application*, and will |
| 392 | check that both the *application* and the server invoking it are conforming to |
| 393 | the WSGI specification and to RFC 2616. |
| 394 | |
| 395 | Any detected nonconformance results in an :exc:`AssertionError` being raised; |
| 396 | note, however, that how these errors are handled is server-dependent. For |
| 397 | example, :mod:`wsgiref.simple_server` and other servers based on |
| 398 | :mod:`wsgiref.handlers` (that don't override the error handling methods to do |
| 399 | something else) will simply output a message that an error has occurred, and |
| 400 | dump the traceback to ``sys.stderr`` or some other error stream. |
| 401 | |
| 402 | This wrapper may also generate output using the :mod:`warnings` module to |
| 403 | indicate behaviors that are questionable but which may not actually be |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 404 | prohibited by :pep:`3333`. Unless they are suppressed using Python command-line |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 405 | options or the :mod:`warnings` API, any such warnings will be written to |
| 406 | ``sys.stderr`` (*not* ``wsgi.errors``, unless they happen to be the same |
| 407 | object). |
| 408 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 409 | Example usage:: |
| 410 | |
| 411 | from wsgiref.validate import validator |
| 412 | from wsgiref.simple_server import make_server |
| 413 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 414 | # Our callable object which is intentionally not compliant to the |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 415 | # standard, so the validator is going to break |
| 416 | def simple_app(environ, start_response): |
Antoine Pitrou | 38a66ad | 2009-01-03 18:41:49 +0000 | [diff] [blame] | 417 | status = b'200 OK' # HTTP Status |
| 418 | headers = [(b'Content-type', b'text/plain')] # HTTP Headers |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 419 | start_response(status, headers) |
| 420 | |
| 421 | # This is going to break because we need to return a list, and |
| 422 | # the validator is going to inform us |
Antoine Pitrou | 38a66ad | 2009-01-03 18:41:49 +0000 | [diff] [blame] | 423 | return b"Hello World" |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 424 | |
| 425 | # This is the application wrapped in a validator |
| 426 | validator_app = validator(simple_app) |
| 427 | |
| 428 | httpd = make_server('', 8000, validator_app) |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 429 | print("Listening on port 8000....") |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 430 | httpd.serve_forever() |
| 431 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 432 | |
| 433 | :mod:`wsgiref.handlers` -- server/gateway base classes |
| 434 | ------------------------------------------------------ |
| 435 | |
| 436 | .. module:: wsgiref.handlers |
| 437 | :synopsis: WSGI server/gateway base classes. |
| 438 | |
| 439 | |
| 440 | This module provides base handler classes for implementing WSGI servers and |
| 441 | gateways. These base classes handle most of the work of communicating with a |
| 442 | WSGI application, as long as they are given a CGI-like environment, along with |
| 443 | input, output, and error streams. |
| 444 | |
| 445 | |
| 446 | .. class:: CGIHandler() |
| 447 | |
| 448 | CGI-based invocation via ``sys.stdin``, ``sys.stdout``, ``sys.stderr`` and |
| 449 | ``os.environ``. This is useful when you have a WSGI application and want to run |
| 450 | it as a CGI script. Simply invoke ``CGIHandler().run(app)``, where ``app`` is |
| 451 | the WSGI application object you wish to invoke. |
| 452 | |
| 453 | This class is a subclass of :class:`BaseCGIHandler` that sets ``wsgi.run_once`` |
| 454 | to true, ``wsgi.multithread`` to false, and ``wsgi.multiprocess`` to true, and |
| 455 | always uses :mod:`sys` and :mod:`os` to obtain the necessary CGI streams and |
| 456 | environment. |
| 457 | |
| 458 | |
Phillip J. Eby | b6d4a8e | 2010-11-03 22:39:01 +0000 | [diff] [blame] | 459 | .. class:: IISCGIHandler() |
| 460 | |
| 461 | A specialized alternative to :class:`CGIHandler`, for use when deploying on |
| 462 | Microsoft's IIS web server, without having set the config allowPathInfo |
| 463 | option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7). |
| 464 | |
| 465 | By default, IIS gives a ``PATH_INFO`` that duplicates the ``SCRIPT_NAME`` at |
| 466 | the front, causing problems for WSGI applications that wish to implement |
| 467 | routing. This handler strips any such duplicated path. |
| 468 | |
| 469 | IIS can be configured to pass the correct ``PATH_INFO``, but this causes |
| 470 | another bug where ``PATH_TRANSLATED`` is wrong. Luckily this variable is |
| 471 | rarely used and is not guaranteed by WSGI. On IIS<7, though, the |
| 472 | setting can only be made on a vhost level, affecting all other script |
| 473 | mappings, many of which break when exposed to the ``PATH_TRANSLATED`` bug. |
| 474 | For this reason IIS<7 is almost never deployed with the fix. (Even IIS7 |
| 475 | rarely uses it because there is still no UI for it.) |
| 476 | |
| 477 | There is no way for CGI code to tell whether the option was set, so a |
| 478 | separate handler class is provided. It is used in the same way as |
| 479 | :class:`CGIHandler`, i.e., by calling ``IISCGIHandler().run(app)``, where |
| 480 | ``app`` is the WSGI application object you wish to invoke. |
| 481 | |
| 482 | .. versionadded:: 3.2 |
| 483 | |
| 484 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 485 | .. class:: BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 486 | |
| 487 | Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and |
| 488 | :mod:`os` modules, the CGI environment and I/O streams are specified explicitly. |
| 489 | The *multithread* and *multiprocess* values are used to set the |
| 490 | ``wsgi.multithread`` and ``wsgi.multiprocess`` flags for any applications run by |
| 491 | the handler instance. |
| 492 | |
| 493 | This class is a subclass of :class:`SimpleHandler` intended for use with |
| 494 | software other than HTTP "origin servers". If you are writing a gateway |
| 495 | protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a |
| 496 | ``Status:`` header to send an HTTP status, you probably want to subclass this |
| 497 | instead of :class:`SimpleHandler`. |
| 498 | |
| 499 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 500 | .. class:: SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 501 | |
| 502 | Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin |
| 503 | servers. If you are writing an HTTP server implementation, you will probably |
| 504 | want to subclass this instead of :class:`BaseCGIHandler` |
| 505 | |
| 506 | This class is a subclass of :class:`BaseHandler`. It overrides the |
| 507 | :meth:`__init__`, :meth:`get_stdin`, :meth:`get_stderr`, :meth:`add_cgi_vars`, |
| 508 | :meth:`_write`, and :meth:`_flush` methods to support explicitly setting the |
| 509 | environment and streams via the constructor. The supplied environment and |
| 510 | streams are stored in the :attr:`stdin`, :attr:`stdout`, :attr:`stderr`, and |
| 511 | :attr:`environ` attributes. |
| 512 | |
| 513 | |
| 514 | .. class:: BaseHandler() |
| 515 | |
| 516 | This is an abstract base class for running WSGI applications. Each instance |
| 517 | will handle a single HTTP request, although in principle you could create a |
| 518 | subclass that was reusable for multiple requests. |
| 519 | |
| 520 | :class:`BaseHandler` instances have only one method intended for external use: |
| 521 | |
| 522 | |
| 523 | .. method:: BaseHandler.run(app) |
| 524 | |
| 525 | Run the specified WSGI application, *app*. |
| 526 | |
| 527 | All of the other :class:`BaseHandler` methods are invoked by this method in the |
| 528 | process of running the application, and thus exist primarily to allow |
| 529 | customizing the process. |
| 530 | |
| 531 | The following methods MUST be overridden in a subclass: |
| 532 | |
| 533 | |
| 534 | .. method:: BaseHandler._write(data) |
| 535 | |
Antoine Pitrou | 38a66ad | 2009-01-03 18:41:49 +0000 | [diff] [blame] | 536 | Buffer the bytes *data* for transmission to the client. It's okay if this |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 537 | method actually transmits the data; :class:`BaseHandler` just separates write |
| 538 | and flush operations for greater efficiency when the underlying system actually |
| 539 | has such a distinction. |
| 540 | |
| 541 | |
| 542 | .. method:: BaseHandler._flush() |
| 543 | |
| 544 | Force buffered data to be transmitted to the client. It's okay if this method |
| 545 | is a no-op (i.e., if :meth:`_write` actually sends the data). |
| 546 | |
| 547 | |
| 548 | .. method:: BaseHandler.get_stdin() |
| 549 | |
| 550 | Return an input stream object suitable for use as the ``wsgi.input`` of the |
| 551 | request currently being processed. |
| 552 | |
| 553 | |
| 554 | .. method:: BaseHandler.get_stderr() |
| 555 | |
| 556 | Return an output stream object suitable for use as the ``wsgi.errors`` of the |
| 557 | request currently being processed. |
| 558 | |
| 559 | |
| 560 | .. method:: BaseHandler.add_cgi_vars() |
| 561 | |
| 562 | Insert CGI variables for the current request into the :attr:`environ` attribute. |
| 563 | |
| 564 | Here are some other methods and attributes you may wish to override. This list |
| 565 | is only a summary, however, and does not include every method that can be |
| 566 | overridden. You should consult the docstrings and source code for additional |
| 567 | information before attempting to create a customized :class:`BaseHandler` |
| 568 | subclass. |
| 569 | |
| 570 | Attributes and methods for customizing the WSGI environment: |
| 571 | |
| 572 | |
| 573 | .. attribute:: BaseHandler.wsgi_multithread |
| 574 | |
| 575 | The value to be used for the ``wsgi.multithread`` environment variable. It |
| 576 | defaults to true in :class:`BaseHandler`, but may have a different default (or |
| 577 | be set by the constructor) in the other subclasses. |
| 578 | |
| 579 | |
| 580 | .. attribute:: BaseHandler.wsgi_multiprocess |
| 581 | |
| 582 | The value to be used for the ``wsgi.multiprocess`` environment variable. It |
| 583 | defaults to true in :class:`BaseHandler`, but may have a different default (or |
| 584 | be set by the constructor) in the other subclasses. |
| 585 | |
| 586 | |
| 587 | .. attribute:: BaseHandler.wsgi_run_once |
| 588 | |
| 589 | The value to be used for the ``wsgi.run_once`` environment variable. It |
| 590 | defaults to false in :class:`BaseHandler`, but :class:`CGIHandler` sets it to |
| 591 | true by default. |
| 592 | |
| 593 | |
| 594 | .. attribute:: BaseHandler.os_environ |
| 595 | |
| 596 | The default environment variables to be included in every request's WSGI |
| 597 | environment. By default, this is a copy of ``os.environ`` at the time that |
| 598 | :mod:`wsgiref.handlers` was imported, but subclasses can either create their own |
| 599 | at the class or instance level. Note that the dictionary should be considered |
| 600 | read-only, since the default value is shared between multiple classes and |
| 601 | instances. |
| 602 | |
| 603 | |
| 604 | .. attribute:: BaseHandler.server_software |
| 605 | |
| 606 | If the :attr:`origin_server` attribute is set, this attribute's value is used to |
| 607 | set the default ``SERVER_SOFTWARE`` WSGI environment variable, and also to set a |
| 608 | default ``Server:`` header in HTTP responses. It is ignored for handlers (such |
| 609 | as :class:`BaseCGIHandler` and :class:`CGIHandler`) that are not HTTP origin |
| 610 | servers. |
| 611 | |
| 612 | |
| 613 | .. method:: BaseHandler.get_scheme() |
| 614 | |
| 615 | Return the URL scheme being used for the current request. The default |
| 616 | implementation uses the :func:`guess_scheme` function from :mod:`wsgiref.util` |
| 617 | to guess whether the scheme should be "http" or "https", based on the current |
| 618 | request's :attr:`environ` variables. |
| 619 | |
| 620 | |
| 621 | .. method:: BaseHandler.setup_environ() |
| 622 | |
| 623 | Set the :attr:`environ` attribute to a fully-populated WSGI environment. The |
| 624 | default implementation uses all of the above methods and attributes, plus the |
| 625 | :meth:`get_stdin`, :meth:`get_stderr`, and :meth:`add_cgi_vars` methods and the |
| 626 | :attr:`wsgi_file_wrapper` attribute. It also inserts a ``SERVER_SOFTWARE`` key |
| 627 | if not present, as long as the :attr:`origin_server` attribute is a true value |
| 628 | and the :attr:`server_software` attribute is set. |
| 629 | |
| 630 | Methods and attributes for customizing exception handling: |
| 631 | |
| 632 | |
| 633 | .. method:: BaseHandler.log_exception(exc_info) |
| 634 | |
| 635 | Log the *exc_info* tuple in the server log. *exc_info* is a ``(type, value, |
| 636 | traceback)`` tuple. The default implementation simply writes the traceback to |
| 637 | the request's ``wsgi.errors`` stream and flushes it. Subclasses can override |
| 638 | this method to change the format or retarget the output, mail the traceback to |
| 639 | an administrator, or whatever other action may be deemed suitable. |
| 640 | |
| 641 | |
| 642 | .. attribute:: BaseHandler.traceback_limit |
| 643 | |
| 644 | The maximum number of frames to include in tracebacks output by the default |
| 645 | :meth:`log_exception` method. If ``None``, all frames are included. |
| 646 | |
| 647 | |
| 648 | .. method:: BaseHandler.error_output(environ, start_response) |
| 649 | |
| 650 | This method is a WSGI application to generate an error page for the user. It is |
| 651 | only invoked if an error occurs before headers are sent to the client. |
| 652 | |
| 653 | This method can access the current error information using ``sys.exc_info()``, |
| 654 | and should pass that information to *start_response* when calling it (as |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 655 | described in the "Error Handling" section of :pep:`3333`). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 656 | |
| 657 | The default implementation just uses the :attr:`error_status`, |
| 658 | :attr:`error_headers`, and :attr:`error_body` attributes to generate an output |
| 659 | page. Subclasses can override this to produce more dynamic error output. |
| 660 | |
| 661 | Note, however, that it's not recommended from a security perspective to spit out |
| 662 | diagnostics to any old user; ideally, you should have to do something special to |
| 663 | enable diagnostic output, which is why the default implementation doesn't |
| 664 | include any. |
| 665 | |
| 666 | |
| 667 | .. attribute:: BaseHandler.error_status |
| 668 | |
| 669 | The HTTP status used for error responses. This should be a status string as |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 670 | defined in :pep:`3333`; it defaults to a 500 code and message. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 671 | |
| 672 | |
| 673 | .. attribute:: BaseHandler.error_headers |
| 674 | |
| 675 | The HTTP headers used for error responses. This should be a list of WSGI |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 676 | response headers (``(name, value)`` tuples), as described in :pep:`3333`. The |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 677 | default list just sets the content type to ``text/plain``. |
| 678 | |
| 679 | |
| 680 | .. attribute:: BaseHandler.error_body |
| 681 | |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 682 | The error response body. This should be an HTTP response body bytestring. It |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 683 | defaults to the plain text, "A server error occurred. Please contact the |
| 684 | administrator." |
| 685 | |
Phillip J. Eby | a01799f | 2010-11-03 00:46:45 +0000 | [diff] [blame] | 686 | Methods and attributes for :pep:`3333`'s "Optional Platform-Specific File |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 687 | Handling" feature: |
| 688 | |
| 689 | |
| 690 | .. attribute:: BaseHandler.wsgi_file_wrapper |
| 691 | |
| 692 | A ``wsgi.file_wrapper`` factory, or ``None``. The default value of this |
| 693 | attribute is the :class:`FileWrapper` class from :mod:`wsgiref.util`. |
| 694 | |
| 695 | |
| 696 | .. method:: BaseHandler.sendfile() |
| 697 | |
| 698 | Override to implement platform-specific file transmission. This method is |
| 699 | called only if the application's return value is an instance of the class |
| 700 | specified by the :attr:`wsgi_file_wrapper` attribute. It should return a true |
| 701 | value if it was able to successfully transmit the file, so that the default |
| 702 | transmission code will not be executed. The default implementation of this |
| 703 | method just returns a false value. |
| 704 | |
| 705 | Miscellaneous methods and attributes: |
| 706 | |
| 707 | |
| 708 | .. attribute:: BaseHandler.origin_server |
| 709 | |
| 710 | This attribute should be set to a true value if the handler's :meth:`_write` and |
| 711 | :meth:`_flush` are being used to communicate directly to the client, rather than |
| 712 | via a CGI-like gateway protocol that wants the HTTP status in a special |
| 713 | ``Status:`` header. |
| 714 | |
| 715 | This attribute's default value is true in :class:`BaseHandler`, but false in |
| 716 | :class:`BaseCGIHandler` and :class:`CGIHandler`. |
| 717 | |
| 718 | |
| 719 | .. attribute:: BaseHandler.http_version |
| 720 | |
| 721 | If :attr:`origin_server` is true, this string attribute is used to set the HTTP |
| 722 | version of the response set to the client. It defaults to ``"1.0"``. |
| 723 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 724 | |
Phillip J. Eby | b6d4a8e | 2010-11-03 22:39:01 +0000 | [diff] [blame] | 725 | .. function:: read_environ() |
| 726 | |
| 727 | Transcode CGI variables from ``os.environ`` to PEP 3333 "bytes in unicode" |
| 728 | strings, returning a new dictionary. This function is used by |
| 729 | :class:`CGIHandler` and :class:`IISCGIHandler` in place of directly using |
| 730 | ``os.environ``, which is not necessarily WSGI-compliant on all platforms |
| 731 | and web servers using Python 3 -- specifically, ones where the OS's |
| 732 | actual environment is Unicode (i.e. Windows), or ones where the environment |
| 733 | is bytes, but the system encoding used by Python to decode it is anything |
| 734 | other than ISO-8859-1 (e.g. Unix systems using UTF-8). |
| 735 | |
| 736 | If you are implementing a CGI-based handler of your own, you probably want |
| 737 | to use this routine instead of just copying values out of ``os.environ`` |
| 738 | directly. |
| 739 | |
| 740 | .. versionadded:: 3.2 |
| 741 | |
| 742 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 743 | Examples |
| 744 | -------- |
| 745 | |
| 746 | This is a working "Hello World" WSGI application:: |
| 747 | |
| 748 | from wsgiref.simple_server import make_server |
| 749 | |
| 750 | # Every WSGI application must have an application object - a callable |
| 751 | # object that accepts two arguments. For that purpose, we're going to |
| 752 | # use a function (note that you're not limited to a function, you can |
| 753 | # use a class for example). The first argument passed to the function |
| 754 | # is a dictionary containing CGI-style envrironment variables and the |
Georg Brandl | 682d7e0 | 2010-10-06 10:26:05 +0000 | [diff] [blame] | 755 | # second variable is the callable object (see PEP 333). |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 756 | def hello_world_app(environ, start_response): |
Antoine Pitrou | 38a66ad | 2009-01-03 18:41:49 +0000 | [diff] [blame] | 757 | status = b'200 OK' # HTTP Status |
| 758 | headers = [(b'Content-type', b'text/plain; charset=utf-8')] # HTTP Headers |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 759 | start_response(status, headers) |
| 760 | |
| 761 | # The returned object is going to be printed |
Antoine Pitrou | 38a66ad | 2009-01-03 18:41:49 +0000 | [diff] [blame] | 762 | return [b"Hello World"] |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 763 | |
| 764 | httpd = make_server('', 8000, hello_world_app) |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 765 | print("Serving on port 8000...") |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 766 | |
| 767 | # Serve until process is killed |
| 768 | httpd.serve_forever() |