cinap_lenrekadd hg and python4bb9e2215 years agoHistory
782 lines · 26.9 KB · TeX
RawDownload
\section{\module{wsgiref} --- WSGI Utilities and ReferenceImplementation}\declaremodule{}{wsgiref}\moduleauthor{Phillip J. Eby}{pje@telecommunity.com}\sectionauthor{Phillip J. Eby}{pje@telecommunity.com}\modulesynopsis{WSGI Utilities and Reference Implementation} \versionadded{2.5} The Web Server Gateway Interface (WSGI) is a standard interfacebetween web server software and web applications written in Python.Having a standard interface makes it easy to use an applicationthat supports WSGI with a number of different web servers. Only authors of web servers and programming frameworks need to knowevery detail and corner case of the WSGI design.  You don't need tounderstand every detail of WSGI just to install a WSGI application orto write a web application using an existing framework. \module{wsgiref} is a reference implementation of the WSGI specificationthat can be used to add WSGI support to a web server or framework.  Itprovides utilities for manipulating WSGI environment variables andresponse headers, base classes for implementing WSGI servers, a demoHTTP server that serves WSGI applications, and a validation tool thatchecks WSGI servers and applications for conformance to theWSGI specification (\pep{333}). % XXX If you're just trying to write a web application... See \url{http://www.wsgi.org} for more information about WSGI,and links to tutorials and other resources.             \subsection{\module{wsgiref.util} -- WSGI environment utilities}\declaremodule{}{wsgiref.util} This module provides a variety of utility functions for working withWSGI environments.  A WSGI environment is a dictionary containingHTTP request variables as described in \pep{333}.  All of the functionstaking an \var{environ} parameter expect a WSGI-compliant dictionary tobe 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 aCGI-like protocol such as FastCGI.  Typically, servers providing suchprotocols will include a \code{HTTPS} variable with a value of ``1''``yes'', or ``on'' when a request is received via SSL.  So, thisfunction 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 isnot 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 URIof 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} andreturn 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 requestURI path, for example to treat the path as a series of dictionary keys.This routine modifies the passed-in environment to make it suitable forinvoking another WSGI application that is located at the target URI.For example, if there is a WSGI application at \code{/foo}, and therequest 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 passingto 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 emptystring and appends a trailing slash to \code{SCRIPT_NAME}, even thoughempty path segments are normally ignored, and \code{SCRIPT_NAME} doesn'tnormally end in a slash.  This is intentional behavior, to ensure thatan application can tell the difference between URIs ending in \code{/x}from ones ending in \code{/x/} when using this routine to do objecttraversal. \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 ofthe \pep{333}-defined \code{wsgi.*} variables.  It only supplies defaultvalues, and does not replace any existing settings for these variables. This routine is intended to make it easier for unit tests of WSGIservers and applications to set up dummy environments.  It should NOTbe 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 miscellaneousutilities: \begin{funcdesc}{is_hop_by_hop}{header_name}Return true if 'header_name' is an HTTP/1.1 ``Hop-by-Hop'' header, asdefined by \rfc{2616}.\end{funcdesc} \begin{classdesc}{FileWrapper}{filelike \optional{, blksize=8192}}A wrapper to convert a file-like object to an iterator.  The resultingobjects 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} parameterwill be repeatedly passed to the \var{filelike} object's \method{read()}method to obtain strings to yield.  When \method{read()} returns anempty string, iteration is ended and is not resumable. If \var{filelike} has a \method{close()} method, the returned objectwill 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 convenientmanipulation of WSGI response headers using a mapping-like interface. \begin{classdesc}{Headers}{headers}Create a mapping-like object wrapping \var{headers}, which must be alist of header name/value tuples as described in \pep{333}.  Any changesmade 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 valueassociated with that header name.  Setting a header deletes any existingvalues for that header, then adds a new value at the end of the wrappedheader list.  Headers' existing order is generally maintained, with newheaders added to the end of the wrapped list. Unlike a dictionary, \class{Headers} objects do not raise an error whenyou try to get or delete a key that isn't in the wrapped header list.Getting a nonexistent header just returns \code{None}, and deletinga 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 thereis a multi-valued header.  The \code{len()} of a \class{Headers} objectis the same as the length of its \method{items()}, which is the sameas 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 formattedstring suitable for transmission as HTTP response headers.  Each headeris 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 thestring is terminated with a blank line. In addition to their mapping interface and formatting features,\class{Headers} objects also have the following methods for queryingand adding multi-valued headers, and for adding headers with MIMEparameters: \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 theoriginal header list or were added to this instance, and may containduplicates.  Any fields deleted and re-inserted are always appended tothe header list.  If no fields exist with the given name, returns anempty list.\end{methoddesc}  \begin{methoddesc}{add_header}{name, value, **_params}Add a (possibly multi-valued) header, with optional MIME parametersspecified via keyword arguments. \var{name} is the header field to add.  Keyword arguments can be used toset MIME parameters for the header field.  Each parameter must be astring or \code{None}.  Underscores in parameter names are converted todashes, since dashes are illegal in Python identifiers, but many MIMEparameter names include dashes.  If the parameter value is a string, itis 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 usedfor 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 serverinstance serves a single WSGI application on a given host and port.  Ifyou want to serve multiple applications on a single host and port, youshould create a WSGI application that parses \code{PATH_INFO} to selectwhich 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 ofthe supplied \var{server_class}, and will process requests using thespecified \var{handler_class}.  \var{app} must be a WSGI applicationobject, 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 killedhttpd.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 thatreturns 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 WSGIapplication correctly.\end{funcdesc}  \begin{classdesc}{WSGIServer}{server_address, RequestHandlerClass}Create a \class{WSGIServer} instance.  \var{server_address} should bea \code{(host,port)} tuple, and \var{RequestHandlerClass} should bethe subclass of \class{BaseHTTPServer.BaseHTTPRequestHandler} that willbe 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 subclassof \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 willreceive 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()}, andthe \method{get_app()} exists mainly for the benefit of request handlerinstances.\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{(\var{host},\var{port})} tuple), and\var{server} (\class{WSGIServer} instance). You do not need to create instances of this class directly; they areautomatically created as needed by \class{WSGIServer} objects.  Youcan, however, subclass this class and supply it as a \var{handler_class}to the \function{make_server()} function.  Some possibly relevantmethods for overriding in subclasses: \begin{methoddesc}{get_environ}{}Returns a dictionary containing the WSGI environment for a request.  Thedefault implementation copies the contents of the \class{WSGIServer}object's \member{base_environ} dictionary attribute and then addsvarious headers derived from the HTTP request.  Each call to this methodshould return a new dictionary containing all of the relevant CGIenvironment 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 handlerinstance using a \module{wsgiref.handlers} class to implement the actualWSGI application interface.\end{methoddesc} \end{classdesc}         \subsection{\module{wsgiref.validate} -- WSGI conformance checker}\declaremodule{}{wsgiref.validate}When creating new WSGI application objects, frameworks, servers, ormiddleware, it can be useful to validate the new code's conformanceusing \module{wsgiref.validate}.  This module provides a function thatcreates WSGI application objects that validate communications betweena WSGI server or gateway and a WSGI application object, to check bothsides for protocol conformance. Note that this utility does not guarantee complete \pep{333} compliance;an absence of errors from this module does not necessarily mean thaterrors do not exist.  However, if this module does produce an error,then it is virtually certain that either the server or application isnot 100\% compliant. This module is based on the \module{paste.lint} module from IanBicking's ``Python Paste'' library. \begin{funcdesc}{validator}{application}Wrap \var{application} and return a new WSGI application object.  Thereturned application will forward all requests to the original\var{application}, and will check that both the \var{application} andthe server invoking it are conforming to the WSGI specification and toRFC 2616. Any detected nonconformance results in an \exception{AssertionError}being raised; note, however, that how these errors are handled isserver-dependent.  For example, \module{wsgiref.simple_server} and otherservers based on \module{wsgiref.handlers} (that don't override theerror handling methods to do something else) will simply output amessage that an error has occurred, and dump the traceback to\code{sys.stderr} or some other error stream. This wrapper may also generate output using the \module{warnings} moduleto indicate behaviors that are questionable but which may not actuallybe prohibited by \pep{333}.  Unless they are suppressed using Pythoncommand-line options or the \module{warnings} API, any such warningswill be written to \code{sys.stderr} (\emph{not} \code{wsgi.errors},unless they happen to be the same object).\end{funcdesc} \subsection{\module{wsgiref.handlers} -- server/gateway base classes}\declaremodule{}{wsgiref.handlers} This module provides base handler classes for implementing WSGI serversand gateways.  These base classes handle most of the work ofcommunicating with a WSGI application, as long as they are given aCGI-like environment, along with input, output, and error streams.  \begin{classdesc}{CGIHandler}{}CGI-based invocation via \code{sys.stdin}, \code{sys.stdout},\code{sys.stderr} and \code{os.environ}.  This is useful when you havea WSGI application and want to run it as a CGI script.  Simply invoke\code{CGIHandler().run(app)}, where \code{app} is the WSGI applicationobject you wish to invoke. This class is a subclass of \class{BaseCGIHandler} that sets\code{wsgi.run_once} to true, \code{wsgi.multithread} to false, and\code{wsgi.multiprocess} to true, and always uses \module{sys} and\module{os} to obtain the necessary CGI streams and environment.\end{classdesc}  \begin{classdesc}{BaseCGIHandler}{stdin, stdout, stderr, environ\optional{, multithread=True \optional{, multiprocess=False}}} Similar to \class{CGIHandler}, but instead of using the \module{sys} and\module{os} modules, the CGI environment and I/O streams are specifiedexplicitly.  The \var{multithread} and \var{multiprocess} values areused to set the \code{wsgi.multithread} and \code{wsgi.multiprocess}flags for any applications run by the handler instance. This class is a subclass of \class{SimpleHandler} intended for use withsoftware other than HTTP ``origin servers''.  If you are writing agateway protocol implementation (such as CGI, FastCGI, SCGI, etc.) thatuses a \code{Status:} header to send an HTTP status, you probably wantto subclass this instead of \class{SimpleHandler}.\end{classdesc}   \begin{classdesc}{SimpleHandler}{stdin, stdout, stderr, environ\optional{,multithread=True \optional{, multiprocess=False}}} Similar to \class{BaseCGIHandler}, but designed for use with HTTP originservers.  If you are writing an HTTP server implementation, you willprobably want to subclass this instead of \class{BaseCGIHandler} This class is a subclass of \class{BaseHandler}.  It overrides the\method{__init__()}, \method{get_stdin()}, \method{get_stderr()},\method{add_cgi_vars()}, \method{_write()}, and \method{_flush()}methods to support explicitly setting the environment and streams viathe constructor.  The supplied environment and streams are stored inthe \member{stdin}, \member{stdout}, \member{stderr}, and\member{environ} attributes.\end{classdesc} \begin{classdesc}{BaseHandler}{}This is an abstract base class for running WSGI applications.  Eachinstance will handle a single HTTP request, although in principle youcould create a subclass that was reusable for multiple requests. \class{BaseHandler} instances have only one method intended for externaluse: \begin{methoddesc}{run}{app}Run the specified WSGI application, \var{app}.\end{methoddesc} All of the other \class{BaseHandler} methods are invoked by this methodin the process of running the application, and thus exist primarily toallow customizing the process. The following methods MUST be overridden in a subclass: \begin{methoddesc}{_write}{data}Buffer the string \var{data} for transmission to the client.  It's okayif this method actually transmits the data; \class{BaseHandler}just separates write and flush operations for greater efficiencywhen the underlying system actually has such a distinction.\end{methoddesc} \begin{methoddesc}{_flush}{}Force buffered data to be transmitted to the client.  It's okay if thismethod is a no-op (i.e., if \method{_write()} actually sends the data).\end{methoddesc} 

Lines 1–500 of 782.