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