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