Instances of WSGIServlet are WSGI applications (by implementing the method __call__() following the WSGI protocol...see PEP 3333).
To create a new subclass of WSGIServlet you must implement, minimally, _lifecycle(). If you want to serve HTML you probably don’t want to subclass WSGIServlet, but rather subclass HTMLPage, which already subclasses WSGIServlet and has many features for generating HTML output. The complete list of subclasses of WSGIServlet in the standard distribution:
- HTMLPage: generates well-formed HTML documents and has many methods and attributes to make generating web pages easy.
- Dispatcher: given a mapping of names to WSGIServlet classes and optionally a document root, subclasses of Dispatcher can serve (dispatch) a mix of static and dynamic content.
- JSONRPCServer: a JSON-RPC service. Subclasses that define methods with names prefixed rpc_ are automatically available to remote clients. These methods can except any arguments and return any object(s) that can be json encoded/decoded.
API:
Abstract base class for all servlets, instances of which are WSGI applications.
WSGIServlet instances are WSGI applications by virtue of the implementation of this method which adheres to the protocol specified in PEP 3333.
Parameters: |
|
---|---|
Return type: | an instance of wsgiservlets.HTTPResponse which are iterable. |
The implementation is simple in principle and follows these steps:
cache environ as environ
create response as an instance of wsgiservlets.HTTPOK
- call, in order:
return response
See __call__() for when this method is called in the life cycle of a request. The base class implementation initializes the form (see: use_form) and the session (see: use_session).
See __call__() for when this method is called in the life cycle of a request. This method is not implemented in the base class and raises NotImplementedError.
See __call__() for when this method is called in the life cycle of a request. The base class implementation garbage collects the form and session objects, if used (see: use_form and use_session).
Specifies the realm for basic HTTP authentication. Default: 'Unspecified'.
If use_form evaluates to True (the default) then for each request form will be set to an instance of cgi.FieldStorage. If False, form will be set to None.
If use_session evaluates to True then for each request session will be set to an instance of Session. If False (the default), session will be set to None.
See use_session.
If sessions are in use (see use_session), then this is the name of the session cookie set on the client.
The client cookie holding the session ID is signed to avoid hijacking session IDs. session_cookie_secret should be unique string to seed the digital string.
Note
used by all servlets accessing the same Session backend
A mapping holding session configuration variables. At this time there are two variables:
- timeout (default: 1800) The amount of time, in seconds, before a session times out.
- hold_exclusive_lock (default: False) If true, a lock will be held through the whole request before being released, thus serializing requests from the same session.
Specifies the type of session to use. Currently, only one kind of session is in the distribution: FileSessionBackend.
Session backend configuration, which is backend specific. For FileSessionBackend the only variable is:
- cachedir (default: /tmp/wsgisrv_sess) which specifies the root directory for session storage.
The class to use when accessing/setting client cookies. Any class can be used, but it should follow the protocol of those classes defined in the standard python library module Cookie. The default is Cookie.SimpleCookie.
Same as environ['REQUEST_METHOD']
Same as environ['SCRIPT_NAME']
Same as environ['PATH_INFO']
Same as environ['QUERY_STRING']
If true (default: False) exceptions will send stack traces and a pretty-printed listing of the environment to the client. Other objects in wsgiservlets also flag debugging output on this variable.
Terse message sent to clients on status 500 responses.
The WSGI environment.
The response object, an instance of HTTPResponse.
An attribute for simplifying access to the incoming HTTP headers. Instead of writing this:
host = self.environ["HTTP_HOST"]
you can write this:
host = self.http_headers.HOST
I.e., keys you would normally look up in environ can be access as attributes of this object with HTTP_ stripped off the variable name. (Actutally, the accessed attribute is looked up case-insensitively, so self.http_headers.hOsT also works.)
Two headers that are not prefaced with HTTP_ can also be accessed via this attribute: CONTENT_TYPE and CONTENT_LENGTH, e.g., self.http_headers.CONTENT_LENGTH.
Note
attributes are read-only. You can not write, e.g., self.http_headers.HOST = ... This will raise an AttributeError.
http_headers also supports the in operator:
if "COOKIE" in self.http_headers:
...
It also support iteration:
for header, value in self.http_headers:
...
Read-only attribute to canonicalize path_info as a list.
Splits path_info and returns it as a list. Empty or all whitespace components or components == “.” are ignored.
Pops the left-most component off path_info and appends it to the end of script_name. Returns the component popped and appended. If count > 1, pops and appends that many components and returns a list of the components. If count is less than one or greater than the number of components in path_info, then no action is taken and None is returned. Examples: with:
script_name = "/a/b/c"
path_info = "/d/e/f"
Then:
Calling Returns Values after call script_name path_info pop_path_info() “d” “/a/b/c/d” “/e/f” pop_path_info(2) [“d”, “e”] “/a/b/c/d/e” “/f” pop_path_info(3) [“d”, “e”, “f”] “/a/b/c/d/e/f” “/” pop_path_info(4) None “/a/b/c” “/d/e/f”
Attribute that processes the COOKIE header and returns a class representing the cookies. Which class is used is defined by cookieclass.
Sets an outgoing cookie.
Parameters: |
|
---|
Deletes a cookie.
Implemented by expiring the cookie; also sets the value to the empty string.
Helper method used in HTTP Basic Authentication.
Parameters: |
|
---|
If the HTTP Authentication header does not have a username/password pair that is found in mapping unauthorized() is called.
Helper method used in HTTP Basic Authentication.
Retrieves username, password pair from HTTP Authentication header.
If the header does not exist, unauthorized() is called. If the header exists, but the username/password pair cannot be base64 decoded, HTTPBadRequest is raised. Otherwise, a tuple is returned: (username, password).
Helper method used in HTTP Basic Authentication.
Writes appropriate HTTP headers requesting authentication and raises HTTPUnauthorized exception. This method does not return.
Send a redirect to the client.
Parameters: |
|
---|
This method does not return.
Redirect internally.
This does not send a redirect to the client (see redirect()), but issues a subrequest to another servlet within the server.
Parameters: |
|
---|
Note
For subrequests, "wsgiservlets.subrequest" will be found in the environment with value True.
This method does not return.
Utility method to write a message to the error log, envrion['wsgi.errors'].
Parameters: |
|
---|
Utility method to write the arguments to the client.
Parameters: |
|
---|
Like write(), but also append a newline.
Parameters: |
|
---|
Return the enivornment formatted: key=val SEP key=val SEP ...
Parameters: |
|
---|
Return the current date and time formatted for a message header.
Sends the file specified by path as the response. If path does not exist, HTTPNotFound is raised. If path is not a file, HTTPForbidden is raised. Otherwise, HTTPOK is raised with the content of the file as the response and Content-Type is set based on path’s extension. This method does not return.
Create a test server.
Parameters: |
|
---|
This method, using wsgiref.simple_server.make_server() from the standard python library, creates a HTTP server. This is very handy when doing quick prototyping of a new class, e.g:
class MyPage(HTMLPage):
...
if __name__ == '__main__':
MyPage.test_server()
After executing the above, you can use your browser and visit http://localhost:8000/.