blob: de74c302502b0a3a12ccd64a8c744e909b69b0b6 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001: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 Brandl116aa622007-08-15 14:28:22 +000010The Web Server Gateway Interface (WSGI) is a standard interface between web
11server software and web applications written in Python. Having a standard
12interface makes it easy to use an application that supports WSGI with a number
13of different web servers.
14
15Only authors of web servers and programming frameworks need to know every detail
16and corner case of the WSGI design. You don't need to understand every detail
17of WSGI just to install a WSGI application or to write a web application using
18an existing framework.
19
20:mod:`wsgiref` is a reference implementation of the WSGI specification that can
21be used to add WSGI support to a web server or framework. It provides utilities
22for manipulating WSGI environment variables and response headers, base classes
23for implementing WSGI servers, a demo HTTP server that serves WSGI applications,
24and a validation tool that checks WSGI servers and applications for conformance
Phillip J. Ebya01799f2010-11-03 00:46:45 +000025to the WSGI specification (:pep:`3333`).
Georg Brandl116aa622007-08-15 14:28:22 +000026
27See http://www.wsgi.org for more information about WSGI, and links to tutorials
28and other resources.
29
Christian Heimes5b5e81c2007-12-31 16:14:33 +000030.. XXX If you're just trying to write a web application...
Georg Brandl116aa622007-08-15 14:28:22 +000031
32
33:mod:`wsgiref.util` -- WSGI environment utilities
34-------------------------------------------------
35
36.. module:: wsgiref.util
37 :synopsis: WSGI environment utilities.
38
39
40This module provides a variety of utility functions for working with WSGI
41environments. A WSGI environment is a dictionary containing HTTP request
Phillip J. Ebya01799f2010-11-03 00:46:45 +000042variables as described in :pep:`3333`. All of the functions taking an *environ*
Georg Brandl116aa622007-08-15 14:28:22 +000043parameter expect a WSGI-compliant dictionary to be supplied; please see
Phillip J. Ebya01799f2010-11-03 00:46:45 +000044:pep:`3333` for a detailed specification.
Georg Brandl116aa622007-08-15 14:28:22 +000045
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 Brandl7f01a132009-09-16 15:58:14 +000060.. function:: request_uri(environ, include_query=True)
Georg Brandl116aa622007-08-15 14:28:22 +000061
62 Return the full request URI, optionally including the query string, using the
Phillip J. Ebya01799f2010-11-03 00:46:45 +000063 algorithm found in the "URL Reconstruction" section of :pep:`3333`. If
Georg Brandl116aa622007-08-15 14:28:22 +000064 *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. Ebya01799f2010-11-03 00:46:45 +0000107 ``PATH_INFO``, and all of the :pep:`3333`\ -defined ``wsgi.*`` variables. It
Georg Brandl116aa622007-08-15 14:28:22 +0000108 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 Heimes7d2ff882007-11-30 14:35:04 +0000115 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
Senthil Kumaran61b5efc2011-05-11 22:27:26 +0800125 status = '200 OK'
126 headers = [('Content-type', 'text/plain; charset=utf-8')]
Christian Heimes7d2ff882007-11-30 14:35:04 +0000127
128 start_response(status, headers)
129
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000130 ret = [("%s: %s\n" % (key, value)).encode("utf-8")
131 for key, value in environ.items()]
Christian Heimes7d2ff882007-11-30 14:35:04 +0000132 return ret
133
134 httpd = make_server('', 8000, simple_app)
Neal Norwitz752abd02008-05-13 04:55:24 +0000135 print("Serving on port 8000...")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000136 httpd.serve_forever()
137
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139In addition to the environment functions above, the :mod:`wsgiref.util` module
140also 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 Brandl7f01a132009-09-16 15:58:14 +0000149.. class:: FileWrapper(filelike, blksize=8192)
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Georg Brandl9afde1c2007-11-01 20:32:30 +0000151 A wrapper to convert a file-like object to an :term:`iterator`. The resulting objects
Georg Brandl116aa622007-08-15 14:28:22 +0000152 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. Ebya01799f2010-11-03 00:46:45 +0000155 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 Brandl116aa622007-08-15 14:28:22 +0000157
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 Heimes7d2ff882007-11-30 14:35:04 +0000162 Example usage::
163
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000164 from io import StringIO
Christian Heimes7d2ff882007-11-30 14:35:04 +0000165 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 Brandl48310cd2009-01-03 21:18:54 +0000171 for chunk in wrapper:
Georg Brandlf6945182008-02-01 11:56:49 +0000172 print(chunk)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000173
174
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176:mod:`wsgiref.headers` -- WSGI response header tools
177----------------------------------------------------
178
179.. module:: wsgiref.headers
180 :synopsis: WSGI response header tools.
181
182
183This module provides a single class, :class:`Headers`, for convenient
184manipulation of WSGI response headers using a mapping-like interface.
185
186
Berker Peksag3e887222014-07-02 08:37:22 +0300187.. class:: Headers([headers])
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189 Create a mapping-like object wrapping *headers*, which must be a list of header
Berker Peksag3e887222014-07-02 08:37:22 +0300190 name/value tuples as described in :pep:`3333`. The default value of *headers* is
191 an empty list.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193 :class:`Headers` objects support typical mapping operations including
194 :meth:`__getitem__`, :meth:`get`, :meth:`__setitem__`, :meth:`setdefault`,
Collin Winterf6b81212007-09-10 00:03:41 +0000195 :meth:`__delitem__` and :meth:`__contains__`. For each of
Georg Brandl116aa622007-08-15 14:28:22 +0000196 these methods, the key is the header name (treated case-insensitively), and the
197 value is the first value associated with that header name. Setting a header
198 deletes any existing values for that header, then adds a new value at the end of
199 the wrapped header list. Headers' existing order is generally maintained, with
200 new headers added to the end of the wrapped list.
201
202 Unlike a dictionary, :class:`Headers` objects do not raise an error when you try
203 to get or delete a key that isn't in the wrapped header list. Getting a
204 nonexistent header just returns ``None``, and deleting a nonexistent header does
205 nothing.
206
207 :class:`Headers` objects also support :meth:`keys`, :meth:`values`, and
208 :meth:`items` methods. The lists returned by :meth:`keys` and :meth:`items` can
209 include the same key more than once if there is a multi-valued header. The
210 ``len()`` of a :class:`Headers` object is the same as the length of its
211 :meth:`items`, which is the same as the length of the wrapped header list. In
212 fact, the :meth:`items` method just returns a copy of the wrapped header list.
213
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000214 Calling ``bytes()`` on a :class:`Headers` object returns a formatted bytestring
Georg Brandl116aa622007-08-15 14:28:22 +0000215 suitable for transmission as HTTP response headers. Each header is placed on a
216 line with its value, separated by a colon and a space. Each line is terminated
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000217 by a carriage return and line feed, and the bytestring is terminated with a
218 blank line.
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220 In addition to their mapping interface and formatting features, :class:`Headers`
221 objects also have the following methods for querying and adding multi-valued
222 headers, and for adding headers with MIME parameters:
223
224
225 .. method:: Headers.get_all(name)
226
227 Return a list of all the values for the named header.
228
229 The returned list will be sorted in the order they appeared in the original
230 header list or were added to this instance, and may contain duplicates. Any
231 fields deleted and re-inserted are always appended to the header list. If no
232 fields exist with the given name, returns an empty list.
233
234
235 .. method:: Headers.add_header(name, value, **_params)
236
237 Add a (possibly multi-valued) header, with optional MIME parameters specified
238 via keyword arguments.
239
240 *name* is the header field to add. Keyword arguments can be used to set MIME
241 parameters for the header field. Each parameter must be a string or ``None``.
242 Underscores in parameter names are converted to dashes, since dashes are illegal
243 in Python identifiers, but many MIME parameter names include dashes. If the
244 parameter value is a string, it is added to the header value parameters in the
245 form ``name="value"``. If it is ``None``, only the parameter name is added.
246 (This is used for MIME parameters without a value.) Example usage::
247
248 h.add_header('content-disposition', 'attachment', filename='bud.gif')
249
250 The above will add a header that looks like this::
251
252 Content-Disposition: attachment; filename="bud.gif"
253
254
Berker Peksag3e887222014-07-02 08:37:22 +0300255 .. versionchanged:: 3.5
256 *headers* parameter is optional.
257
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259:mod:`wsgiref.simple_server` -- a simple WSGI HTTP server
260---------------------------------------------------------
261
262.. module:: wsgiref.simple_server
263 :synopsis: A simple WSGI HTTP server.
264
265
Georg Brandl24420152008-05-26 16:32:26 +0000266This module implements a simple HTTP server (based on :mod:`http.server`)
Georg Brandl116aa622007-08-15 14:28:22 +0000267that serves WSGI applications. Each server instance serves a single WSGI
268application on a given host and port. If you want to serve multiple
269applications on a single host and port, you should create a WSGI application
270that parses ``PATH_INFO`` to select which application to invoke for each
271request. (E.g., using the :func:`shift_path_info` function from
272:mod:`wsgiref.util`.)
273
274
Georg Brandl7f01a132009-09-16 15:58:14 +0000275.. function:: make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277 Create a new WSGI server listening on *host* and *port*, accepting connections
278 for *app*. The return value is an instance of the supplied *server_class*, and
279 will process requests using the specified *handler_class*. *app* must be a WSGI
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000280 application object, as defined by :pep:`3333`.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282 Example usage::
283
284 from wsgiref.simple_server import make_server, demo_app
285
286 httpd = make_server('', 8000, demo_app)
Collin Winterc79461b2007-09-01 23:34:30 +0000287 print("Serving HTTP on port 8000...")
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289 # Respond to requests until process is killed
290 httpd.serve_forever()
291
292 # Alternative: serve one request, then exit
Christian Heimes7d2ff882007-11-30 14:35:04 +0000293 httpd.handle_request()
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295
296.. function:: demo_app(environ, start_response)
297
298 This function is a small but complete WSGI application that returns a text page
299 containing the message "Hello world!" and a list of the key/value pairs provided
300 in the *environ* parameter. It's useful for verifying that a WSGI server (such
301 as :mod:`wsgiref.simple_server`) is able to run a simple WSGI application
302 correctly.
303
304
305.. class:: WSGIServer(server_address, RequestHandlerClass)
306
307 Create a :class:`WSGIServer` instance. *server_address* should be a
308 ``(host,port)`` tuple, and *RequestHandlerClass* should be the subclass of
Georg Brandl24420152008-05-26 16:32:26 +0000309 :class:`http.server.BaseHTTPRequestHandler` that will be used to process
Georg Brandl116aa622007-08-15 14:28:22 +0000310 requests.
311
312 You do not normally need to call this constructor, as the :func:`make_server`
313 function can handle all the details for you.
314
Georg Brandl24420152008-05-26 16:32:26 +0000315 :class:`WSGIServer` is a subclass of :class:`http.server.HTTPServer`, so all
Georg Brandl116aa622007-08-15 14:28:22 +0000316 of its methods (such as :meth:`serve_forever` and :meth:`handle_request`) are
317 available. :class:`WSGIServer` also provides these WSGI-specific methods:
318
319
320 .. method:: WSGIServer.set_app(application)
321
322 Sets the callable *application* as the WSGI application that will receive
323 requests.
324
325
326 .. method:: WSGIServer.get_app()
327
328 Returns the currently-set application callable.
329
330 Normally, however, you do not need to use these additional methods, as
331 :meth:`set_app` is normally called by :func:`make_server`, and the
332 :meth:`get_app` exists mainly for the benefit of request handler instances.
333
334
335.. class:: WSGIRequestHandler(request, client_address, server)
336
337 Create an HTTP handler for the given *request* (i.e. a socket), *client_address*
338 (a ``(host,port)`` tuple), and *server* (:class:`WSGIServer` instance).
339
340 You do not need to create instances of this class directly; they are
341 automatically created as needed by :class:`WSGIServer` objects. You can,
342 however, subclass this class and supply it as a *handler_class* to the
343 :func:`make_server` function. Some possibly relevant methods for overriding in
344 subclasses:
345
346
347 .. method:: WSGIRequestHandler.get_environ()
348
349 Returns a dictionary containing the WSGI environment for a request. The default
350 implementation copies the contents of the :class:`WSGIServer` object's
351 :attr:`base_environ` dictionary attribute and then adds various headers derived
352 from the HTTP request. Each call to this method should return a new dictionary
353 containing all of the relevant CGI environment variables as specified in
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000354 :pep:`3333`.
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356
357 .. method:: WSGIRequestHandler.get_stderr()
358
359 Return the object that should be used as the ``wsgi.errors`` stream. The default
360 implementation just returns ``sys.stderr``.
361
362
363 .. method:: WSGIRequestHandler.handle()
364
365 Process the HTTP request. The default implementation creates a handler instance
366 using a :mod:`wsgiref.handlers` class to implement the actual WSGI application
367 interface.
368
369
370:mod:`wsgiref.validate` --- WSGI conformance checker
371----------------------------------------------------
372
373.. module:: wsgiref.validate
374 :synopsis: WSGI conformance checker.
375
376
377When creating new WSGI application objects, frameworks, servers, or middleware,
378it can be useful to validate the new code's conformance using
379:mod:`wsgiref.validate`. This module provides a function that creates WSGI
380application objects that validate communications between a WSGI server or
381gateway and a WSGI application object, to check both sides for protocol
382conformance.
383
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000384Note that this utility does not guarantee complete :pep:`3333` compliance; an
Georg Brandl116aa622007-08-15 14:28:22 +0000385absence of errors from this module does not necessarily mean that errors do not
386exist. However, if this module does produce an error, then it is virtually
387certain that either the server or application is not 100% compliant.
388
389This module is based on the :mod:`paste.lint` module from Ian Bicking's "Python
390Paste" library.
391
392
393.. function:: validator(application)
394
395 Wrap *application* and return a new WSGI application object. The returned
396 application will forward all requests to the original *application*, and will
397 check that both the *application* and the server invoking it are conforming to
398 the WSGI specification and to RFC 2616.
399
400 Any detected nonconformance results in an :exc:`AssertionError` being raised;
401 note, however, that how these errors are handled is server-dependent. For
402 example, :mod:`wsgiref.simple_server` and other servers based on
403 :mod:`wsgiref.handlers` (that don't override the error handling methods to do
404 something else) will simply output a message that an error has occurred, and
405 dump the traceback to ``sys.stderr`` or some other error stream.
406
407 This wrapper may also generate output using the :mod:`warnings` module to
408 indicate behaviors that are questionable but which may not actually be
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000409 prohibited by :pep:`3333`. Unless they are suppressed using Python command-line
Georg Brandl116aa622007-08-15 14:28:22 +0000410 options or the :mod:`warnings` API, any such warnings will be written to
411 ``sys.stderr`` (*not* ``wsgi.errors``, unless they happen to be the same
412 object).
413
Christian Heimes7d2ff882007-11-30 14:35:04 +0000414 Example usage::
415
416 from wsgiref.validate import validator
417 from wsgiref.simple_server import make_server
418
Georg Brandl48310cd2009-01-03 21:18:54 +0000419 # Our callable object which is intentionally not compliant to the
Christian Heimes7d2ff882007-11-30 14:35:04 +0000420 # standard, so the validator is going to break
421 def simple_app(environ, start_response):
Senthil Kumaran61b5efc2011-05-11 22:27:26 +0800422 status = '200 OK' # HTTP Status
423 headers = [('Content-type', 'text/plain')] # HTTP Headers
Christian Heimes7d2ff882007-11-30 14:35:04 +0000424 start_response(status, headers)
425
426 # This is going to break because we need to return a list, and
427 # the validator is going to inform us
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000428 return b"Hello World"
Christian Heimes7d2ff882007-11-30 14:35:04 +0000429
430 # This is the application wrapped in a validator
431 validator_app = validator(simple_app)
432
433 httpd = make_server('', 8000, validator_app)
Georg Brandlf6945182008-02-01 11:56:49 +0000434 print("Listening on port 8000....")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000435 httpd.serve_forever()
436
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438:mod:`wsgiref.handlers` -- server/gateway base classes
439------------------------------------------------------
440
441.. module:: wsgiref.handlers
442 :synopsis: WSGI server/gateway base classes.
443
444
445This module provides base handler classes for implementing WSGI servers and
446gateways. These base classes handle most of the work of communicating with a
447WSGI application, as long as they are given a CGI-like environment, along with
448input, output, and error streams.
449
450
451.. class:: CGIHandler()
452
453 CGI-based invocation via ``sys.stdin``, ``sys.stdout``, ``sys.stderr`` and
454 ``os.environ``. This is useful when you have a WSGI application and want to run
455 it as a CGI script. Simply invoke ``CGIHandler().run(app)``, where ``app`` is
456 the WSGI application object you wish to invoke.
457
458 This class is a subclass of :class:`BaseCGIHandler` that sets ``wsgi.run_once``
459 to true, ``wsgi.multithread`` to false, and ``wsgi.multiprocess`` to true, and
460 always uses :mod:`sys` and :mod:`os` to obtain the necessary CGI streams and
461 environment.
462
463
Phillip J. Ebyb6d4a8e2010-11-03 22:39:01 +0000464.. class:: IISCGIHandler()
465
466 A specialized alternative to :class:`CGIHandler`, for use when deploying on
467 Microsoft's IIS web server, without having set the config allowPathInfo
468 option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7).
469
470 By default, IIS gives a ``PATH_INFO`` that duplicates the ``SCRIPT_NAME`` at
471 the front, causing problems for WSGI applications that wish to implement
472 routing. This handler strips any such duplicated path.
473
474 IIS can be configured to pass the correct ``PATH_INFO``, but this causes
475 another bug where ``PATH_TRANSLATED`` is wrong. Luckily this variable is
476 rarely used and is not guaranteed by WSGI. On IIS<7, though, the
477 setting can only be made on a vhost level, affecting all other script
478 mappings, many of which break when exposed to the ``PATH_TRANSLATED`` bug.
479 For this reason IIS<7 is almost never deployed with the fix. (Even IIS7
480 rarely uses it because there is still no UI for it.)
481
482 There is no way for CGI code to tell whether the option was set, so a
483 separate handler class is provided. It is used in the same way as
484 :class:`CGIHandler`, i.e., by calling ``IISCGIHandler().run(app)``, where
485 ``app`` is the WSGI application object you wish to invoke.
486
487 .. versionadded:: 3.2
488
489
Georg Brandl7f01a132009-09-16 15:58:14 +0000490.. class:: BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000491
492 Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and
493 :mod:`os` modules, the CGI environment and I/O streams are specified explicitly.
494 The *multithread* and *multiprocess* values are used to set the
495 ``wsgi.multithread`` and ``wsgi.multiprocess`` flags for any applications run by
496 the handler instance.
497
498 This class is a subclass of :class:`SimpleHandler` intended for use with
499 software other than HTTP "origin servers". If you are writing a gateway
500 protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a
501 ``Status:`` header to send an HTTP status, you probably want to subclass this
502 instead of :class:`SimpleHandler`.
503
504
Georg Brandl7f01a132009-09-16 15:58:14 +0000505.. class:: SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000506
507 Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin
508 servers. If you are writing an HTTP server implementation, you will probably
509 want to subclass this instead of :class:`BaseCGIHandler`
510
511 This class is a subclass of :class:`BaseHandler`. It overrides the
512 :meth:`__init__`, :meth:`get_stdin`, :meth:`get_stderr`, :meth:`add_cgi_vars`,
513 :meth:`_write`, and :meth:`_flush` methods to support explicitly setting the
514 environment and streams via the constructor. The supplied environment and
515 streams are stored in the :attr:`stdin`, :attr:`stdout`, :attr:`stderr`, and
516 :attr:`environ` attributes.
517
518
519.. class:: BaseHandler()
520
521 This is an abstract base class for running WSGI applications. Each instance
522 will handle a single HTTP request, although in principle you could create a
523 subclass that was reusable for multiple requests.
524
525 :class:`BaseHandler` instances have only one method intended for external use:
526
527
528 .. method:: BaseHandler.run(app)
529
530 Run the specified WSGI application, *app*.
531
532 All of the other :class:`BaseHandler` methods are invoked by this method in the
533 process of running the application, and thus exist primarily to allow
534 customizing the process.
535
536 The following methods MUST be overridden in a subclass:
537
538
539 .. method:: BaseHandler._write(data)
540
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000541 Buffer the bytes *data* for transmission to the client. It's okay if this
Georg Brandl116aa622007-08-15 14:28:22 +0000542 method actually transmits the data; :class:`BaseHandler` just separates write
543 and flush operations for greater efficiency when the underlying system actually
544 has such a distinction.
545
546
547 .. method:: BaseHandler._flush()
548
549 Force buffered data to be transmitted to the client. It's okay if this method
550 is a no-op (i.e., if :meth:`_write` actually sends the data).
551
552
553 .. method:: BaseHandler.get_stdin()
554
555 Return an input stream object suitable for use as the ``wsgi.input`` of the
556 request currently being processed.
557
558
559 .. method:: BaseHandler.get_stderr()
560
561 Return an output stream object suitable for use as the ``wsgi.errors`` of the
562 request currently being processed.
563
564
565 .. method:: BaseHandler.add_cgi_vars()
566
567 Insert CGI variables for the current request into the :attr:`environ` attribute.
568
569 Here are some other methods and attributes you may wish to override. This list
570 is only a summary, however, and does not include every method that can be
571 overridden. You should consult the docstrings and source code for additional
572 information before attempting to create a customized :class:`BaseHandler`
573 subclass.
574
575 Attributes and methods for customizing the WSGI environment:
576
577
578 .. attribute:: BaseHandler.wsgi_multithread
579
580 The value to be used for the ``wsgi.multithread`` environment variable. It
581 defaults to true in :class:`BaseHandler`, but may have a different default (or
582 be set by the constructor) in the other subclasses.
583
584
585 .. attribute:: BaseHandler.wsgi_multiprocess
586
587 The value to be used for the ``wsgi.multiprocess`` environment variable. It
588 defaults to true in :class:`BaseHandler`, but may have a different default (or
589 be set by the constructor) in the other subclasses.
590
591
592 .. attribute:: BaseHandler.wsgi_run_once
593
594 The value to be used for the ``wsgi.run_once`` environment variable. It
595 defaults to false in :class:`BaseHandler`, but :class:`CGIHandler` sets it to
596 true by default.
597
598
599 .. attribute:: BaseHandler.os_environ
600
601 The default environment variables to be included in every request's WSGI
602 environment. By default, this is a copy of ``os.environ`` at the time that
603 :mod:`wsgiref.handlers` was imported, but subclasses can either create their own
604 at the class or instance level. Note that the dictionary should be considered
605 read-only, since the default value is shared between multiple classes and
606 instances.
607
608
609 .. attribute:: BaseHandler.server_software
610
611 If the :attr:`origin_server` attribute is set, this attribute's value is used to
612 set the default ``SERVER_SOFTWARE`` WSGI environment variable, and also to set a
613 default ``Server:`` header in HTTP responses. It is ignored for handlers (such
614 as :class:`BaseCGIHandler` and :class:`CGIHandler`) that are not HTTP origin
615 servers.
616
Senthil Kumarana5e0eaf2012-07-07 14:29:58 -0700617 .. versionchanged:: 3.3
Senthil Kumaranac3f4f32012-07-08 01:32:57 -0700618 The term "Python" is replaced with implementation specific term like
619 "CPython", "Jython" etc.
Georg Brandl116aa622007-08-15 14:28:22 +0000620
621 .. method:: BaseHandler.get_scheme()
622
623 Return the URL scheme being used for the current request. The default
624 implementation uses the :func:`guess_scheme` function from :mod:`wsgiref.util`
625 to guess whether the scheme should be "http" or "https", based on the current
626 request's :attr:`environ` variables.
627
628
629 .. method:: BaseHandler.setup_environ()
630
631 Set the :attr:`environ` attribute to a fully-populated WSGI environment. The
632 default implementation uses all of the above methods and attributes, plus the
633 :meth:`get_stdin`, :meth:`get_stderr`, and :meth:`add_cgi_vars` methods and the
634 :attr:`wsgi_file_wrapper` attribute. It also inserts a ``SERVER_SOFTWARE`` key
635 if not present, as long as the :attr:`origin_server` attribute is a true value
636 and the :attr:`server_software` attribute is set.
637
638 Methods and attributes for customizing exception handling:
639
640
641 .. method:: BaseHandler.log_exception(exc_info)
642
643 Log the *exc_info* tuple in the server log. *exc_info* is a ``(type, value,
644 traceback)`` tuple. The default implementation simply writes the traceback to
645 the request's ``wsgi.errors`` stream and flushes it. Subclasses can override
646 this method to change the format or retarget the output, mail the traceback to
647 an administrator, or whatever other action may be deemed suitable.
648
649
650 .. attribute:: BaseHandler.traceback_limit
651
652 The maximum number of frames to include in tracebacks output by the default
653 :meth:`log_exception` method. If ``None``, all frames are included.
654
655
656 .. method:: BaseHandler.error_output(environ, start_response)
657
658 This method is a WSGI application to generate an error page for the user. It is
659 only invoked if an error occurs before headers are sent to the client.
660
661 This method can access the current error information using ``sys.exc_info()``,
662 and should pass that information to *start_response* when calling it (as
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000663 described in the "Error Handling" section of :pep:`3333`).
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665 The default implementation just uses the :attr:`error_status`,
666 :attr:`error_headers`, and :attr:`error_body` attributes to generate an output
667 page. Subclasses can override this to produce more dynamic error output.
668
669 Note, however, that it's not recommended from a security perspective to spit out
670 diagnostics to any old user; ideally, you should have to do something special to
671 enable diagnostic output, which is why the default implementation doesn't
672 include any.
673
674
675 .. attribute:: BaseHandler.error_status
676
677 The HTTP status used for error responses. This should be a status string as
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000678 defined in :pep:`3333`; it defaults to a 500 code and message.
Georg Brandl116aa622007-08-15 14:28:22 +0000679
680
681 .. attribute:: BaseHandler.error_headers
682
683 The HTTP headers used for error responses. This should be a list of WSGI
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000684 response headers (``(name, value)`` tuples), as described in :pep:`3333`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000685 default list just sets the content type to ``text/plain``.
686
687
688 .. attribute:: BaseHandler.error_body
689
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000690 The error response body. This should be an HTTP response body bytestring. It
Georg Brandl116aa622007-08-15 14:28:22 +0000691 defaults to the plain text, "A server error occurred. Please contact the
692 administrator."
693
Phillip J. Ebya01799f2010-11-03 00:46:45 +0000694 Methods and attributes for :pep:`3333`'s "Optional Platform-Specific File
Georg Brandl116aa622007-08-15 14:28:22 +0000695 Handling" feature:
696
697
698 .. attribute:: BaseHandler.wsgi_file_wrapper
699
700 A ``wsgi.file_wrapper`` factory, or ``None``. The default value of this
Éric Araujo16190c82011-04-25 19:05:53 +0200701 attribute is the :class:`wsgiref.util.FileWrapper` class.
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703
704 .. method:: BaseHandler.sendfile()
705
706 Override to implement platform-specific file transmission. This method is
707 called only if the application's return value is an instance of the class
708 specified by the :attr:`wsgi_file_wrapper` attribute. It should return a true
709 value if it was able to successfully transmit the file, so that the default
710 transmission code will not be executed. The default implementation of this
711 method just returns a false value.
712
713 Miscellaneous methods and attributes:
714
715
716 .. attribute:: BaseHandler.origin_server
717
718 This attribute should be set to a true value if the handler's :meth:`_write` and
719 :meth:`_flush` are being used to communicate directly to the client, rather than
720 via a CGI-like gateway protocol that wants the HTTP status in a special
721 ``Status:`` header.
722
723 This attribute's default value is true in :class:`BaseHandler`, but false in
724 :class:`BaseCGIHandler` and :class:`CGIHandler`.
725
726
727 .. attribute:: BaseHandler.http_version
728
729 If :attr:`origin_server` is true, this string attribute is used to set the HTTP
730 version of the response set to the client. It defaults to ``"1.0"``.
731
Christian Heimes7d2ff882007-11-30 14:35:04 +0000732
Phillip J. Ebyb6d4a8e2010-11-03 22:39:01 +0000733.. function:: read_environ()
734
735 Transcode CGI variables from ``os.environ`` to PEP 3333 "bytes in unicode"
736 strings, returning a new dictionary. This function is used by
737 :class:`CGIHandler` and :class:`IISCGIHandler` in place of directly using
738 ``os.environ``, which is not necessarily WSGI-compliant on all platforms
739 and web servers using Python 3 -- specifically, ones where the OS's
740 actual environment is Unicode (i.e. Windows), or ones where the environment
741 is bytes, but the system encoding used by Python to decode it is anything
742 other than ISO-8859-1 (e.g. Unix systems using UTF-8).
743
744 If you are implementing a CGI-based handler of your own, you probably want
745 to use this routine instead of just copying values out of ``os.environ``
746 directly.
747
748 .. versionadded:: 3.2
749
750
Christian Heimes7d2ff882007-11-30 14:35:04 +0000751Examples
752--------
753
754This is a working "Hello World" WSGI application::
755
756 from wsgiref.simple_server import make_server
757
758 # Every WSGI application must have an application object - a callable
759 # object that accepts two arguments. For that purpose, we're going to
760 # use a function (note that you're not limited to a function, you can
761 # use a class for example). The first argument passed to the function
Berker Peksag4882cac2015-04-14 09:30:01 +0300762 # is a dictionary containing CGI-style environment variables and the
Georg Brandl682d7e02010-10-06 10:26:05 +0000763 # second variable is the callable object (see PEP 333).
Christian Heimes7d2ff882007-11-30 14:35:04 +0000764 def hello_world_app(environ, start_response):
Senthil Kumaran61b5efc2011-05-11 22:27:26 +0800765 status = '200 OK' # HTTP Status
766 headers = [('Content-type', 'text/plain; charset=utf-8')] # HTTP Headers
Christian Heimes7d2ff882007-11-30 14:35:04 +0000767 start_response(status, headers)
768
769 # The returned object is going to be printed
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000770 return [b"Hello World"]
Christian Heimes7d2ff882007-11-30 14:35:04 +0000771
772 httpd = make_server('', 8000, hello_world_app)
Georg Brandlf6945182008-02-01 11:56:49 +0000773 print("Serving on port 8000...")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000774
775 # Serve until process is killed
776 httpd.serve_forever()