/Doc/library/wsgiref.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 728 lines · 481 code · 247 blank · 0 comment · 0 complexity · 81a69b587354083e293759396215b3a9 MD5 · raw file

  1. :mod:`wsgiref` --- WSGI Utilities and Reference Implementation
  2. ==============================================================
  3. .. module:: wsgiref
  4. :synopsis: WSGI Utilities and Reference Implementation.
  5. .. moduleauthor:: Phillip J. Eby <pje@telecommunity.com>
  6. .. sectionauthor:: Phillip J. Eby <pje@telecommunity.com>
  7. .. versionadded:: 2.5
  8. The Web Server Gateway Interface (WSGI) is a standard interface between web
  9. server software and web applications written in Python. Having a standard
  10. interface makes it easy to use an application that supports WSGI with a number
  11. of different web servers.
  12. Only authors of web servers and programming frameworks need to know every detail
  13. and corner case of the WSGI design. You don't need to understand every detail
  14. of WSGI just to install a WSGI application or to write a web application using
  15. an existing framework.
  16. :mod:`wsgiref` is a reference implementation of the WSGI specification that can
  17. be used to add WSGI support to a web server or framework. It provides utilities
  18. for manipulating WSGI environment variables and response headers, base classes
  19. for implementing WSGI servers, a demo HTTP server that serves WSGI applications,
  20. and a validation tool that checks WSGI servers and applications for conformance
  21. to the WSGI specification (:pep:`333`).
  22. See http://www.wsgi.org for more information about WSGI, and links to tutorials
  23. and other resources.
  24. .. XXX If you're just trying to write a web application...
  25. :mod:`wsgiref.util` -- WSGI environment utilities
  26. -------------------------------------------------
  27. .. module:: wsgiref.util
  28. :synopsis: WSGI environment utilities.
  29. This module provides a variety of utility functions for working with WSGI
  30. environments. A WSGI environment is a dictionary containing HTTP request
  31. variables as described in :pep:`333`. All of the functions taking an *environ*
  32. parameter expect a WSGI-compliant dictionary to be supplied; please see
  33. :pep:`333` for a detailed specification.
  34. .. function:: guess_scheme(environ)
  35. Return a guess for whether ``wsgi.url_scheme`` should be "http" or "https", by
  36. checking for a ``HTTPS`` environment variable in the *environ* dictionary. The
  37. return value is a string.
  38. This function is useful when creating a gateway that wraps CGI or a CGI-like
  39. protocol such as FastCGI. Typically, servers providing such protocols will
  40. include a ``HTTPS`` variable with a value of "1" "yes", or "on" when a request
  41. is received via SSL. So, this function returns "https" if such a value is
  42. found, and "http" otherwise.
  43. .. function:: request_uri(environ [, include_query=1])
  44. Return the full request URI, optionally including the query string, using the
  45. algorithm found in the "URL Reconstruction" section of :pep:`333`. If
  46. *include_query* is false, the query string is not included in the resulting URI.
  47. .. function:: application_uri(environ)
  48. Similar to :func:`request_uri`, except that the ``PATH_INFO`` and
  49. ``QUERY_STRING`` variables are ignored. The result is the base URI of the
  50. application object addressed by the request.
  51. .. function:: shift_path_info(environ)
  52. Shift a single name from ``PATH_INFO`` to ``SCRIPT_NAME`` and return the name.
  53. The *environ* dictionary is *modified* in-place; use a copy if you need to keep
  54. the original ``PATH_INFO`` or ``SCRIPT_NAME`` intact.
  55. If there are no remaining path segments in ``PATH_INFO``, ``None`` is returned.
  56. Typically, this routine is used to process each portion of a request URI path,
  57. for example to treat the path as a series of dictionary keys. This routine
  58. modifies the passed-in environment to make it suitable for invoking another WSGI
  59. application that is located at the target URI. For example, if there is a WSGI
  60. application at ``/foo``, and the request URI path is ``/foo/bar/baz``, and the
  61. WSGI application at ``/foo`` calls :func:`shift_path_info`, it will receive the
  62. string "bar", and the environment will be updated to be suitable for passing to
  63. a WSGI application at ``/foo/bar``. That is, ``SCRIPT_NAME`` will change from
  64. ``/foo`` to ``/foo/bar``, and ``PATH_INFO`` will change from ``/bar/baz`` to
  65. ``/baz``.
  66. When ``PATH_INFO`` is just a "/", this routine returns an empty string and
  67. appends a trailing slash to ``SCRIPT_NAME``, even though empty path segments are
  68. normally ignored, and ``SCRIPT_NAME`` doesn't normally end in a slash. This is
  69. intentional behavior, to ensure that an application can tell the difference
  70. between URIs ending in ``/x`` from ones ending in ``/x/`` when using this
  71. routine to do object traversal.
  72. .. function:: setup_testing_defaults(environ)
  73. Update *environ* with trivial defaults for testing purposes.
  74. This routine adds various parameters required for WSGI, including ``HTTP_HOST``,
  75. ``SERVER_NAME``, ``SERVER_PORT``, ``REQUEST_METHOD``, ``SCRIPT_NAME``,
  76. ``PATH_INFO``, and all of the :pep:`333`\ -defined ``wsgi.*`` variables. It
  77. only supplies default values, and does not replace any existing settings for
  78. these variables.
  79. This routine is intended to make it easier for unit tests of WSGI servers and
  80. applications to set up dummy environments. It should NOT be used by actual WSGI
  81. servers or applications, since the data is fake!
  82. Example usage::
  83. from wsgiref.util import setup_testing_defaults
  84. from wsgiref.simple_server import make_server
  85. # A relatively simple WSGI application. It's going to print out the
  86. # environment dictionary after being updated by setup_testing_defaults
  87. def simple_app(environ, start_response):
  88. setup_testing_defaults(environ)
  89. status = '200 OK'
  90. headers = [('Content-type', 'text/plain')]
  91. start_response(status, headers)
  92. ret = ["%s: %s\n" % (key, value)
  93. for key, value in environ.iteritems()]
  94. return ret
  95. httpd = make_server('', 8000, simple_app)
  96. print "Serving on port 8000..."
  97. httpd.serve_forever()
  98. In addition to the environment functions above, the :mod:`wsgiref.util` module
  99. also provides these miscellaneous utilities:
  100. .. function:: is_hop_by_hop(header_name)
  101. Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header, as defined by
  102. :rfc:`2616`.
  103. .. class:: FileWrapper(filelike [, blksize=8192])
  104. A wrapper to convert a file-like object to an :term:`iterator`. The resulting objects
  105. support both :meth:`__getitem__` and :meth:`__iter__` iteration styles, for
  106. compatibility with Python 2.1 and Jython. As the object is iterated over, the
  107. optional *blksize* parameter will be repeatedly passed to the *filelike*
  108. object's :meth:`read` method to obtain strings to yield. When :meth:`read`
  109. returns an empty string, iteration is ended and is not resumable.
  110. If *filelike* has a :meth:`close` method, the returned object will also have a
  111. :meth:`close` method, and it will invoke the *filelike* object's :meth:`close`
  112. method when called.
  113. Example usage::
  114. from StringIO import StringIO
  115. from wsgiref.util import FileWrapper
  116. # We're using a StringIO-buffer for as the file-like object
  117. filelike = StringIO("This is an example file-like object"*10)
  118. wrapper = FileWrapper(filelike, blksize=5)
  119. for chunk in wrapper:
  120. print chunk
  121. :mod:`wsgiref.headers` -- WSGI response header tools
  122. ----------------------------------------------------
  123. .. module:: wsgiref.headers
  124. :synopsis: WSGI response header tools.
  125. This module provides a single class, :class:`Headers`, for convenient
  126. manipulation of WSGI response headers using a mapping-like interface.
  127. .. class:: Headers(headers)
  128. Create a mapping-like object wrapping *headers*, which must be a list of header
  129. name/value tuples as described in :pep:`333`. Any changes made to the new
  130. :class:`Headers` object will directly update the *headers* list it was created
  131. with.
  132. :class:`Headers` objects support typical mapping operations including
  133. :meth:`__getitem__`, :meth:`get`, :meth:`__setitem__`, :meth:`setdefault`,
  134. :meth:`__delitem__`, :meth:`__contains__` and :meth:`has_key`. For each of
  135. these methods, the key is the header name (treated case-insensitively), and the
  136. value is the first value associated with that header name. Setting a header
  137. deletes any existing values for that header, then adds a new value at the end of
  138. the wrapped header list. Headers' existing order is generally maintained, with
  139. new headers added to the end of the wrapped list.
  140. Unlike a dictionary, :class:`Headers` objects do not raise an error when you try
  141. to get or delete a key that isn't in the wrapped header list. Getting a
  142. nonexistent header just returns ``None``, and deleting a nonexistent header does
  143. nothing.
  144. :class:`Headers` objects also support :meth:`keys`, :meth:`values`, and
  145. :meth:`items` methods. The lists returned by :meth:`keys` and :meth:`items` can
  146. include the same key more than once if there is a multi-valued header. The
  147. ``len()`` of a :class:`Headers` object is the same as the length of its
  148. :meth:`items`, which is the same as the length of the wrapped header list. In
  149. fact, the :meth:`items` method just returns a copy of the wrapped header list.
  150. Calling ``str()`` on a :class:`Headers` object returns a formatted string
  151. suitable for transmission as HTTP response headers. Each header is placed on a
  152. line with its value, separated by a colon and a space. Each line is terminated
  153. by a carriage return and line feed, and the string is terminated with a blank
  154. line.
  155. In addition to their mapping interface and formatting features, :class:`Headers`
  156. objects also have the following methods for querying and adding multi-valued
  157. headers, and for adding headers with MIME parameters:
  158. .. method:: Headers.get_all(name)
  159. Return a list of all the values for the named header.
  160. The returned list will be sorted in the order they appeared in the original
  161. header list or were added to this instance, and may contain duplicates. Any
  162. fields deleted and re-inserted are always appended to the header list. If no
  163. fields exist with the given name, returns an empty list.
  164. .. method:: Headers.add_header(name, value, **_params)
  165. Add a (possibly multi-valued) header, with optional MIME parameters specified
  166. via keyword arguments.
  167. *name* is the header field to add. Keyword arguments can be used to set MIME
  168. parameters for the header field. Each parameter must be a string or ``None``.
  169. Underscores in parameter names are converted to dashes, since dashes are illegal
  170. in Python identifiers, but many MIME parameter names include dashes. If the
  171. parameter value is a string, it is added to the header value parameters in the
  172. form ``name="value"``. If it is ``None``, only the parameter name is added.
  173. (This is used for MIME parameters without a value.) Example usage::
  174. h.add_header('content-disposition', 'attachment', filename='bud.gif')
  175. The above will add a header that looks like this::
  176. Content-Disposition: attachment; filename="bud.gif"
  177. :mod:`wsgiref.simple_server` -- a simple WSGI HTTP server
  178. ---------------------------------------------------------
  179. .. module:: wsgiref.simple_server
  180. :synopsis: A simple WSGI HTTP server.
  181. This module implements a simple HTTP server (based on :mod:`BaseHTTPServer`)
  182. that serves WSGI applications. Each server instance serves a single WSGI
  183. application on a given host and port. If you want to serve multiple
  184. applications on a single host and port, you should create a WSGI application
  185. that parses ``PATH_INFO`` to select which application to invoke for each
  186. request. (E.g., using the :func:`shift_path_info` function from
  187. :mod:`wsgiref.util`.)
  188. .. function:: make_server(host, port, app [, server_class=WSGIServer [, handler_class=WSGIRequestHandler]])
  189. Create a new WSGI server listening on *host* and *port*, accepting connections
  190. for *app*. The return value is an instance of the supplied *server_class*, and
  191. will process requests using the specified *handler_class*. *app* must be a WSGI
  192. application object, as defined by :pep:`333`.
  193. Example usage::
  194. from wsgiref.simple_server import make_server, demo_app
  195. httpd = make_server('', 8000, demo_app)
  196. print "Serving HTTP on port 8000..."
  197. # Respond to requests until process is killed
  198. httpd.serve_forever()
  199. # Alternative: serve one request, then exit
  200. httpd.handle_request()
  201. .. function:: demo_app(environ, start_response)
  202. This function is a small but complete WSGI application that returns a text page
  203. containing the message "Hello world!" and a list of the key/value pairs provided
  204. in the *environ* parameter. It's useful for verifying that a WSGI server (such
  205. as :mod:`wsgiref.simple_server`) is able to run a simple WSGI application
  206. correctly.
  207. .. class:: WSGIServer(server_address, RequestHandlerClass)
  208. Create a :class:`WSGIServer` instance. *server_address* should be a
  209. ``(host,port)`` tuple, and *RequestHandlerClass* should be the subclass of
  210. :class:`BaseHTTPServer.BaseHTTPRequestHandler` that will be used to process
  211. requests.
  212. You do not normally need to call this constructor, as the :func:`make_server`
  213. function can handle all the details for you.
  214. :class:`WSGIServer` is a subclass of :class:`BaseHTTPServer.HTTPServer`, so all
  215. of its methods (such as :meth:`serve_forever` and :meth:`handle_request`) are
  216. available. :class:`WSGIServer` also provides these WSGI-specific methods:
  217. .. method:: WSGIServer.set_app(application)
  218. Sets the callable *application* as the WSGI application that will receive
  219. requests.
  220. .. method:: WSGIServer.get_app()
  221. Returns the currently-set application callable.
  222. Normally, however, you do not need to use these additional methods, as
  223. :meth:`set_app` is normally called by :func:`make_server`, and the
  224. :meth:`get_app` exists mainly for the benefit of request handler instances.
  225. .. class:: WSGIRequestHandler(request, client_address, server)
  226. Create an HTTP handler for the given *request* (i.e. a socket), *client_address*
  227. (a ``(host,port)`` tuple), and *server* (:class:`WSGIServer` instance).
  228. You do not need to create instances of this class directly; they are
  229. automatically created as needed by :class:`WSGIServer` objects. You can,
  230. however, subclass this class and supply it as a *handler_class* to the
  231. :func:`make_server` function. Some possibly relevant methods for overriding in
  232. subclasses:
  233. .. method:: WSGIRequestHandler.get_environ()
  234. Returns a dictionary containing the WSGI environment for a request. The default
  235. implementation copies the contents of the :class:`WSGIServer` object's
  236. :attr:`base_environ` dictionary attribute and then adds various headers derived
  237. from the HTTP request. Each call to this method should return a new dictionary
  238. containing all of the relevant CGI environment variables as specified in
  239. :pep:`333`.
  240. .. method:: WSGIRequestHandler.get_stderr()
  241. Return the object that should be used as the ``wsgi.errors`` stream. The default
  242. implementation just returns ``sys.stderr``.
  243. .. method:: WSGIRequestHandler.handle()
  244. Process the HTTP request. The default implementation creates a handler instance
  245. using a :mod:`wsgiref.handlers` class to implement the actual WSGI application
  246. interface.
  247. :mod:`wsgiref.validate` --- WSGI conformance checker
  248. ----------------------------------------------------
  249. .. module:: wsgiref.validate
  250. :synopsis: WSGI conformance checker.
  251. When creating new WSGI application objects, frameworks, servers, or middleware,
  252. it can be useful to validate the new code's conformance using
  253. :mod:`wsgiref.validate`. This module provides a function that creates WSGI
  254. application objects that validate communications between a WSGI server or
  255. gateway and a WSGI application object, to check both sides for protocol
  256. conformance.
  257. Note that this utility does not guarantee complete :pep:`333` compliance; an
  258. absence of errors from this module does not necessarily mean that errors do not
  259. exist. However, if this module does produce an error, then it is virtually
  260. certain that either the server or application is not 100% compliant.
  261. This module is based on the :mod:`paste.lint` module from Ian Bicking's "Python
  262. Paste" library.
  263. .. function:: validator(application)
  264. Wrap *application* and return a new WSGI application object. The returned
  265. application will forward all requests to the original *application*, and will
  266. check that both the *application* and the server invoking it are conforming to
  267. the WSGI specification and to RFC 2616.
  268. Any detected nonconformance results in an :exc:`AssertionError` being raised;
  269. note, however, that how these errors are handled is server-dependent. For
  270. example, :mod:`wsgiref.simple_server` and other servers based on
  271. :mod:`wsgiref.handlers` (that don't override the error handling methods to do
  272. something else) will simply output a message that an error has occurred, and
  273. dump the traceback to ``sys.stderr`` or some other error stream.
  274. This wrapper may also generate output using the :mod:`warnings` module to
  275. indicate behaviors that are questionable but which may not actually be
  276. prohibited by :pep:`333`. Unless they are suppressed using Python command-line
  277. options or the :mod:`warnings` API, any such warnings will be written to
  278. ``sys.stderr`` (*not* ``wsgi.errors``, unless they happen to be the same
  279. object).
  280. Example usage::
  281. from wsgiref.validate import validator
  282. from wsgiref.simple_server import make_server
  283. # Our callable object which is intentionally not compliant to the
  284. # standard, so the validator is going to break
  285. def simple_app(environ, start_response):
  286. status = '200 OK' # HTTP Status
  287. headers = [('Content-type', 'text/plain')] # HTTP Headers
  288. start_response(status, headers)
  289. # This is going to break because we need to return a list, and
  290. # the validator is going to inform us
  291. return "Hello World"
  292. # This is the application wrapped in a validator
  293. validator_app = validator(simple_app)
  294. httpd = make_server('', 8000, validator_app)
  295. print "Listening on port 8000...."
  296. httpd.serve_forever()
  297. :mod:`wsgiref.handlers` -- server/gateway base classes
  298. ------------------------------------------------------
  299. .. module:: wsgiref.handlers
  300. :synopsis: WSGI server/gateway base classes.
  301. This module provides base handler classes for implementing WSGI servers and
  302. gateways. These base classes handle most of the work of communicating with a
  303. WSGI application, as long as they are given a CGI-like environment, along with
  304. input, output, and error streams.
  305. .. class:: CGIHandler()
  306. CGI-based invocation via ``sys.stdin``, ``sys.stdout``, ``sys.stderr`` and
  307. ``os.environ``. This is useful when you have a WSGI application and want to run
  308. it as a CGI script. Simply invoke ``CGIHandler().run(app)``, where ``app`` is
  309. the WSGI application object you wish to invoke.
  310. This class is a subclass of :class:`BaseCGIHandler` that sets ``wsgi.run_once``
  311. to true, ``wsgi.multithread`` to false, and ``wsgi.multiprocess`` to true, and
  312. always uses :mod:`sys` and :mod:`os` to obtain the necessary CGI streams and
  313. environment.
  314. .. class:: BaseCGIHandler(stdin, stdout, stderr, environ [, multithread=True [, multiprocess=False]])
  315. Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and
  316. :mod:`os` modules, the CGI environment and I/O streams are specified explicitly.
  317. The *multithread* and *multiprocess* values are used to set the
  318. ``wsgi.multithread`` and ``wsgi.multiprocess`` flags for any applications run by
  319. the handler instance.
  320. This class is a subclass of :class:`SimpleHandler` intended for use with
  321. software other than HTTP "origin servers". If you are writing a gateway
  322. protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a
  323. ``Status:`` header to send an HTTP status, you probably want to subclass this
  324. instead of :class:`SimpleHandler`.
  325. .. class:: SimpleHandler(stdin, stdout, stderr, environ [,multithread=True [, multiprocess=False]])
  326. Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin
  327. servers. If you are writing an HTTP server implementation, you will probably
  328. want to subclass this instead of :class:`BaseCGIHandler`
  329. This class is a subclass of :class:`BaseHandler`. It overrides the
  330. :meth:`__init__`, :meth:`get_stdin`, :meth:`get_stderr`, :meth:`add_cgi_vars`,
  331. :meth:`_write`, and :meth:`_flush` methods to support explicitly setting the
  332. environment and streams via the constructor. The supplied environment and
  333. streams are stored in the :attr:`stdin`, :attr:`stdout`, :attr:`stderr`, and
  334. :attr:`environ` attributes.
  335. .. class:: BaseHandler()
  336. This is an abstract base class for running WSGI applications. Each instance
  337. will handle a single HTTP request, although in principle you could create a
  338. subclass that was reusable for multiple requests.
  339. :class:`BaseHandler` instances have only one method intended for external use:
  340. .. method:: BaseHandler.run(app)
  341. Run the specified WSGI application, *app*.
  342. All of the other :class:`BaseHandler` methods are invoked by this method in the
  343. process of running the application, and thus exist primarily to allow
  344. customizing the process.
  345. The following methods MUST be overridden in a subclass:
  346. .. method:: BaseHandler._write(data)
  347. Buffer the string *data* for transmission to the client. It's okay if this
  348. method actually transmits the data; :class:`BaseHandler` just separates write
  349. and flush operations for greater efficiency when the underlying system actually
  350. has such a distinction.
  351. .. method:: BaseHandler._flush()
  352. Force buffered data to be transmitted to the client. It's okay if this method
  353. is a no-op (i.e., if :meth:`_write` actually sends the data).
  354. .. method:: BaseHandler.get_stdin()
  355. Return an input stream object suitable for use as the ``wsgi.input`` of the
  356. request currently being processed.
  357. .. method:: BaseHandler.get_stderr()
  358. Return an output stream object suitable for use as the ``wsgi.errors`` of the
  359. request currently being processed.
  360. .. method:: BaseHandler.add_cgi_vars()
  361. Insert CGI variables for the current request into the :attr:`environ` attribute.
  362. Here are some other methods and attributes you may wish to override. This list
  363. is only a summary, however, and does not include every method that can be
  364. overridden. You should consult the docstrings and source code for additional
  365. information before attempting to create a customized :class:`BaseHandler`
  366. subclass.
  367. Attributes and methods for customizing the WSGI environment:
  368. .. attribute:: BaseHandler.wsgi_multithread
  369. The value to be used for the ``wsgi.multithread`` environment variable. It
  370. defaults to true in :class:`BaseHandler`, but may have a different default (or
  371. be set by the constructor) in the other subclasses.
  372. .. attribute:: BaseHandler.wsgi_multiprocess
  373. The value to be used for the ``wsgi.multiprocess`` environment variable. It
  374. defaults to true in :class:`BaseHandler`, but may have a different default (or
  375. be set by the constructor) in the other subclasses.
  376. .. attribute:: BaseHandler.wsgi_run_once
  377. The value to be used for the ``wsgi.run_once`` environment variable. It
  378. defaults to false in :class:`BaseHandler`, but :class:`CGIHandler` sets it to
  379. true by default.
  380. .. attribute:: BaseHandler.os_environ
  381. The default environment variables to be included in every request's WSGI
  382. environment. By default, this is a copy of ``os.environ`` at the time that
  383. :mod:`wsgiref.handlers` was imported, but subclasses can either create their own
  384. at the class or instance level. Note that the dictionary should be considered
  385. read-only, since the default value is shared between multiple classes and
  386. instances.
  387. .. attribute:: BaseHandler.server_software
  388. If the :attr:`origin_server` attribute is set, this attribute's value is used to
  389. set the default ``SERVER_SOFTWARE`` WSGI environment variable, and also to set a
  390. default ``Server:`` header in HTTP responses. It is ignored for handlers (such
  391. as :class:`BaseCGIHandler` and :class:`CGIHandler`) that are not HTTP origin
  392. servers.
  393. .. method:: BaseHandler.get_scheme()
  394. Return the URL scheme being used for the current request. The default
  395. implementation uses the :func:`guess_scheme` function from :mod:`wsgiref.util`
  396. to guess whether the scheme should be "http" or "https", based on the current
  397. request's :attr:`environ` variables.
  398. .. method:: BaseHandler.setup_environ()
  399. Set the :attr:`environ` attribute to a fully-populated WSGI environment. The
  400. default implementation uses all of the above methods and attributes, plus the
  401. :meth:`get_stdin`, :meth:`get_stderr`, and :meth:`add_cgi_vars` methods and the
  402. :attr:`wsgi_file_wrapper` attribute. It also inserts a ``SERVER_SOFTWARE`` key
  403. if not present, as long as the :attr:`origin_server` attribute is a true value
  404. and the :attr:`server_software` attribute is set.
  405. Methods and attributes for customizing exception handling:
  406. .. method:: BaseHandler.log_exception(exc_info)
  407. Log the *exc_info* tuple in the server log. *exc_info* is a ``(type, value,
  408. traceback)`` tuple. The default implementation simply writes the traceback to
  409. the request's ``wsgi.errors`` stream and flushes it. Subclasses can override
  410. this method to change the format or retarget the output, mail the traceback to
  411. an administrator, or whatever other action may be deemed suitable.
  412. .. attribute:: BaseHandler.traceback_limit
  413. The maximum number of frames to include in tracebacks output by the default
  414. :meth:`log_exception` method. If ``None``, all frames are included.
  415. .. method:: BaseHandler.error_output(environ, start_response)
  416. This method is a WSGI application to generate an error page for the user. It is
  417. only invoked if an error occurs before headers are sent to the client.
  418. This method can access the current error information using ``sys.exc_info()``,
  419. and should pass that information to *start_response* when calling it (as
  420. described in the "Error Handling" section of :pep:`333`).
  421. The default implementation just uses the :attr:`error_status`,
  422. :attr:`error_headers`, and :attr:`error_body` attributes to generate an output
  423. page. Subclasses can override this to produce more dynamic error output.
  424. Note, however, that it's not recommended from a security perspective to spit out
  425. diagnostics to any old user; ideally, you should have to do something special to
  426. enable diagnostic output, which is why the default implementation doesn't
  427. include any.
  428. .. attribute:: BaseHandler.error_status
  429. The HTTP status used for error responses. This should be a status string as
  430. defined in :pep:`333`; it defaults to a 500 code and message.
  431. .. attribute:: BaseHandler.error_headers
  432. The HTTP headers used for error responses. This should be a list of WSGI
  433. response headers (``(name, value)`` tuples), as described in :pep:`333`. The
  434. default list just sets the content type to ``text/plain``.
  435. .. attribute:: BaseHandler.error_body
  436. The error response body. This should be an HTTP response body string. It
  437. defaults to the plain text, "A server error occurred. Please contact the
  438. administrator."
  439. Methods and attributes for :pep:`333`'s "Optional Platform-Specific File
  440. Handling" feature:
  441. .. attribute:: BaseHandler.wsgi_file_wrapper
  442. A ``wsgi.file_wrapper`` factory, or ``None``. The default value of this
  443. attribute is the :class:`FileWrapper` class from :mod:`wsgiref.util`.
  444. .. method:: BaseHandler.sendfile()
  445. Override to implement platform-specific file transmission. This method is
  446. called only if the application's return value is an instance of the class
  447. specified by the :attr:`wsgi_file_wrapper` attribute. It should return a true
  448. value if it was able to successfully transmit the file, so that the default
  449. transmission code will not be executed. The default implementation of this
  450. method just returns a false value.
  451. Miscellaneous methods and attributes:
  452. .. attribute:: BaseHandler.origin_server
  453. This attribute should be set to a true value if the handler's :meth:`_write` and
  454. :meth:`_flush` are being used to communicate directly to the client, rather than
  455. via a CGI-like gateway protocol that wants the HTTP status in a special
  456. ``Status:`` header.
  457. This attribute's default value is true in :class:`BaseHandler`, but false in
  458. :class:`BaseCGIHandler` and :class:`CGIHandler`.
  459. .. attribute:: BaseHandler.http_version
  460. If :attr:`origin_server` is true, this string attribute is used to set the HTTP
  461. version of the response set to the client. It defaults to ``"1.0"``.
  462. Examples
  463. --------
  464. This is a working "Hello World" WSGI application::
  465. from wsgiref.simple_server import make_server
  466. # Every WSGI application must have an application object - a callable
  467. # object that accepts two arguments. For that purpose, we're going to
  468. # use a function (note that you're not limited to a function, you can
  469. # use a class for example). The first argument passed to the function
  470. # is a dictionary containing CGI-style envrironment variables and the
  471. # second variable is the callable object (see PEP333)
  472. def hello_world_app(environ, start_response):
  473. status = '200 OK' # HTTP Status
  474. headers = [('Content-type', 'text/plain')] # HTTP Headers
  475. start_response(status, headers)
  476. # The returned object is going to be printed
  477. return ["Hello World"]
  478. httpd = make_server('', 8000, hello_world_app)
  479. print "Serving on port 8000..."
  480. # Serve until process is killed
  481. httpd.serve_forever()