Debian Codegraph @

Doc/library/wsgiref.rst

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