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