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