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