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