summaryrefslogtreecommitdiff
path: root/docs/libwsgiref.tex
blob: ba9f194e0ab4fcdfa74489282fbbcf192f9b591a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
\section{\module{wsgiref} --- WSGI Utilities and Reference
Implementation}
\declaremodule{}{wsgiref}
\moduleauthor{Phillip J. Eby}{pje@telecommunity.com}
\sectionauthor{Phillip J. Eby}{pje@telecommunity.com}
\modulesynopsis{WSGI Utilities and Reference Implementation}

The Web Server Gateway Interface (WSGI) is a standard interface
between web server software and web applications written in Python.
Having a standard interface makes it easy to use a WSGI-supporting
application with a number of different web servers.

Only authors of web servers and programming frameworks need to know
every detail and corner case of the WSGI design.  You don't need to
understand every detail of WSGI just to install a WSGI application or
to write a web application using an existing framework.

\module{wsgiref} is a reference implementation of the WSGI specification
that can be used to add WSGI support to a web server or framework.  It
provides utilities for manipulating WSGI environment variables and
response headers, base classes for implementing WSGI servers, a demo
HTTP server that serves WSGI applications, and a validation tool that
checks WSGI servers and applications for conformance to the
WSGI specification (\pep{333}).

% XXX If you're just trying to write a web application...
% XXX should create a URL on python.org to point people to.














\subsection{\module{wsgiref.util} -- WSGI environment utilities}
\declaremodule{}{wsgiref.util}

This module provides a variety of utility functions for working with
WSGI environments.  A WSGI environment is a dictionary containing
HTTP request variables as described in \pep{333}.  All of the functions
taking an \var{environ} parameter expect a WSGI-compliant dictionary to
be supplied; please see \pep{333} for a detailed specification.

\begin{funcdesc}{guess_scheme}{environ}
Return a guess for whether \code{wsgi.url_scheme} should be ``http'' or
``https'', by checking for a \code{HTTPS} environment variable in the
\var{environ} dictionary.  The return value is a string.

This function is useful when creating a gateway that wraps CGI or a
CGI-like protocol such as FastCGI.  Typically, servers providing such
protocols will include a \code{HTTPS} variable with a value of ``1''
``yes'', or ``on'' when a request is received via SSL.  So, this
function returns ``https'' if such a value is found, and ``http''
otherwise.
\end{funcdesc}

\begin{funcdesc}{request_uri}{environ \optional{, include_query=1}}
Return the full request URI, optionally including the query string,
using the algorithm found in the ``URL Reconstruction'' section of
\pep{333}.  If \var{include_query} is false, the query string is
not included in the resulting URI.
\end{funcdesc}

\begin{funcdesc}{application_uri}{environ}
Similar to \function{request_uri}, except that the \code{PATH_INFO} and
\code{QUERY_STRING} variables are ignored.  The result is the base URI
of the application object addressed by the request.
\end{funcdesc}

\begin{funcdesc}{shift_path_info}{environ}
Shift a single name from \code{PATH_INFO} to \code{SCRIPT_NAME} and
return the name.  The \var{environ} dictionary is \emph{modified}
in-place; use a copy if you need to keep the original \code{PATH_INFO}
or \code{SCRIPT_NAME} intact.

If there are no remaining path segments in \code{PATH_INFO}, \code{None}
is returned.

Typically, this routine is used to process each portion of a request
URI path, for example to treat the path as a series of dictionary keys.
This routine modifies the passed-in environment to make it suitable for
invoking another WSGI application that is located at the target URI.
For example, if there is a WSGI application at \code{/foo}, and the
request URI path is \code{/foo/bar/baz}, and the WSGI application at
\code{/foo} calls \function{shift_path_info}, it will receive the string
``bar'', and the environment will be updated to be suitable for passing
to a WSGI application at \code{/foo/bar}.  That is, \code{SCRIPT_NAME}
will change from \code{/foo} to \code{/foo/bar}, and \code{PATH_INFO}
will change from \code{/bar/baz} to \code{/baz}.

When \code{PATH_INFO} is just a ``/'', this routine returns an empty
string and appends a trailing slash to \code{SCRIPT_NAME}, even though
empty path segments are normally ignored, and \code{SCRIPT_NAME} doesn't
normally end in a slash.  This is intentional behavior, to ensure that
an application can tell the difference between URIs ending in \code{/x}
from ones ending in \code{/x/} when using this routine to do object
traversal.

\end{funcdesc}

\begin{funcdesc}{setup_testing_defaults}{environ}
Update \var{environ} with trivial defaults for testing purposes.

This routine adds various parameters required for WSGI, including
\code{HTTP_HOST}, \code{SERVER_NAME}, \code{SERVER_PORT},
\code{REQUEST_METHOD}, \code{SCRIPT_NAME}, \code{PATH_INFO}, and all of
the \pep{333}-defined \code{wsgi.*} variables.  It only supplies default
values, and does not replace any existing settings for these variables.

This routine is intended to make it easier for unit tests of WSGI
servers and applications to set up dummy environments.  It should NOT
be used by actual WSGI servers or applications, since the data is fake!
\end{funcdesc}



In addition to the environment functions above, the
\module{wsgiref.util} module also provides these miscellaneous
utilities:

\begin{funcdesc}{is_hop_by_hop}{header_name}
Return true if 'header_name' is an HTTP/1.1 ``Hop-by-Hop'' header, as
defined by \rfc{2616}.
\end{funcdesc}

\begin{classdesc}{FileWrapper}{filelike \optional{, blksize=8192}}
A wrapper to convert a file-like object to an iterator.  The resulting
objects support both \method{__getitem__} and \method{__iter__}
iteration styles, for compatibility with Python 2.1 and Jython.
As the object is iterated over, the optional \var{blksize} parameter
will be repeatedly passed to the \var{filelike} object's \method{read()}
method to obtain strings to yield.  When \method{read()} returns an
empty string, iteration is ended and is not resumable.

If \var{filelike} has a \method{close()} method, the returned object
will also have a \method{close()} method, and it will invoke the
\var{filelike} object's \method{close()} method when called.
\end{classdesc}



















\subsection{\module{wsgiref.headers} -- WSGI response header tools}
\declaremodule{}{wsgiref.headers}

This module provides a single class, \class{Headers}, for convenient
manipulation of WSGI response headers using a mapping-like interface.

\begin{classdesc}{Headers}{headers}
Create a mapping-like object wrapping \var{headers}, which must be a
list of header name/value tuples as described in \pep{333}.  Any changes
made to the new \class{Headers} object will directly update the
\var{headers} list it was created with.

\class{Headers} objects support typical mapping operations including
\method{__getitem__}, \method{get}, \method{__setitem__},
\method{setdefault}, \method{__delitem__}, \method{__contains__} and
\method{has_key}.  For each of these methods, the key is the header name
(treated case-insensitively), and the value is the first value
associated with that header name.  Setting a header deletes any existing
values for that header, then adds a new value at the end of the wrapped
header list.  Headers' existing order is generally maintained, with new
headers added to the end of the wrapped list.

Unlike a dictionary, \class{Headers} objects do not raise an error when
you try to get or delete a key that isn't in the wrapped header list.
Getting a nonexistent header just returns \code{None}, and deleting
a nonexistent header does nothing.

\class{Headers} objects also support \method{keys()}, \method{values()},
and \method{items()} methods.  The lists returned by \method{keys()}
and \method{items()} can include the same key more than once if there
is a multi-valued header.  The \code{len()} of a \class{Headers} object
is the same as the length of its \method{items()}, which is the same
as the length of the wrapped header list.  In fact, the \method{items()}
method just returns a copy of the wrapped header list.

Calling \code{str()} on a \class{Headers} object returns a formatted
string suitable for transmission as HTTP response headers.  Each header
is placed on a line with its value, separated by a colon and a space.
Each line is terminated by a carriage return and line feed, and the
string is terminated with a blank line.

In addition to their mapping interface and formatting features,
\class{Headers} objects also have the following methods for querying
and adding multi-valued headers, and for adding headers with MIME
parameters:

\begin{methoddesc}{get_all}{name}
Return a list of all the values for the named header.

The returned list will be sorted in the order they appeared in the
original header list or were added to this instance, and may contain
duplicates.  Any fields deleted and re-inserted are always appended to
the header list.  If no fields exist with the given name, returns an
empty list.
\end{methoddesc}


\begin{methoddesc}{add_header}{name, value, **_params}
Add a (possibly multi-valued) header, with optional MIME parameters
specified via keyword arguments.

\var{name} is the header field to add.  Keyword arguments can be used to
set MIME parameters for the header field.  Each parameter must be a
string or \code{None}.  Underscores in parameter names are converted to
dashes, since dashes are illegal in Python identifiers, but many MIME
parameter names include dashes.  If the parameter value is a string, it
is added to the header value parameters in the form \code{name="value"}.
If it is \code{None}, only the parameter name is added.  (This is used
for MIME parameters without a value.)  Example usage:

\begin{verbatim}
h.add_header('content-disposition', 'attachment', filename='bud.gif')
\end{verbatim}

The above will add a header that looks like this:

\begin{verbatim}
Content-Disposition: attachment; filename="bud.gif"
\end{verbatim}
\end{methoddesc}
\end{classdesc}

\subsection{\module{wsgiref.simple_server} -- a simple WSGI HTTP server}
\declaremodule[wsgiref.simpleserver]{}{wsgiref.simple_server}

This module implements a simple HTTP server (based on
\module{BaseHTTPServer}) that serves WSGI applications.  Each server
instance serves a single WSGI application on a given host and port.  If
you want to serve multiple applications on a single host and port, you
should create a WSGI application that parses \code{PATH_INFO} to select
which application to invoke for each request.  (E.g., using the
\function{shift_path_info()} function from \module{wsgiref.util}.)


\begin{funcdesc}{make_server}{host, port, app
\optional{, server_class=\class{WSGIServer} \optional{,
handler_class=\class{WSGIRequestHandler}}}}
Create a new WSGI server listening on \var{host} and \var{port},
accepting connections for \var{app}.  The return value is an instance of
the supplied \var{server_class}, and will process requests using the
specified \var{handler_class}.  \var{app} must be a WSGI application
object, as defined by \pep{333}.

Example usage:
\begin{verbatim}from wsgiref.simple_server import make_server, demo_app

httpd = make_server('', 8000, demo_app)
print "Serving HTTP on port 8000..."

# Respond to requests until process is killed
httpd.serve_forever()

# Alternative: serve one request, then exit
##httpd.handle_request()
\end{verbatim}

\end{funcdesc}






\begin{funcdesc}{demo_app}{environ, start_response}
This function is a small but complete WSGI application that
returns a text page containing the message ``Hello world!''
and a list of the key/value pairs provided in the
\var{environ} parameter.  It's useful for verifying that a WSGI server
(such as \module{wsgiref.simple_server}) is able to run a simple WSGI
application correctly.
\end{funcdesc}


\begin{classdesc}{WSGIServer}{server_address, RequestHandlerClass}
Create a \class{WSGIServer} instance.  \var{server_address} should be
a \code{(host,port)} tuple, and \var{RequestHandlerClass} should be
the subclass of \class{BaseHTTPServer.BaseHTTPRequestHandler} that will
be used to process requests.

You do not normally need to call this constructor, as the
\function{make_server()} function can handle all the details for you.

\class{WSGIServer} is a subclass
of \class{BaseHTTPServer.HTTPServer}, so all of its methods (such as
\method{serve_forever()} and \method{handle_request()}) are available.
\class{WSGIServer} also provides these WSGI-specific methods:

\begin{methoddesc}{set_app}{application}
Sets the callable \var{application} as the WSGI application that will
receive requests.
\end{methoddesc}

\begin{methoddesc}{get_app}{}
Returns the currently-set application callable.
\end{methoddesc}

Normally, however, you do not need to use these additional methods, as
\method{set_app()} is normally called by \function{make_server()}, and
the \method{get_app()} exists mainly for the benefit of request handler
instances.
\end{classdesc}



\begin{classdesc}{WSGIRequestHandler}{request, client_address, server}
Create an HTTP handler for the given \var{request} (i.e. a socket),
\var{client_address} (a \code{(host,port)} tuple), and \var{server}
(\class{WSGIServer} instance).

You do not need to create instances of this class directly; they are
automatically created as needed by \class{WSGIServer} objects.  You
can, however, subclass this class and supply it as a \var{handler_class}
to the \function{make_server()} function.  Some possibly relevant
methods for overriding in subclasses:

\begin{methoddesc}{get_environ}{}
Returns a dictionary containing the WSGI environment for a request.  The
default implementation copies the contents of the \class{WSGIServer}
object's \member{base_environ} dictionary attribute and then adds
various headers derived from the HTTP request.  Each call to this method
should return a new dictionary containing all of the relevant CGI
environment variables as specified in \pep{333}.
\end{methoddesc}

\begin{methoddesc}{get_stderr}{}
Return the object that should be used as the \code{wsgi.errors} stream.
The default implementation just returns \code{sys.stderr}.
\end{methoddesc}

\begin{methoddesc}{handle}{}
Process the HTTP request.  The default implementation creates a handler
instance using a \module{wsgiref.handlers} class to implement the actual
WSGI application interface.
\end{methoddesc}

\end{classdesc}









\subsection{\module{wsgiref.validate} -- WSGI conformance checker}
\declaremodule{}{wsgiref.validate}

\begin{funcdesc}{middleware}{application}
\end{funcdesc}




































\subsection{\module{wsgiref.handlers} -- server/gateway base classes}
\declaremodule{}{wsgiref.handlers}