wsgiservlets.WSGIServlet

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:

class wsgiservlets.WSGIServlet

Abstract base class for all servlets, instances of which are WSGI applications.

__call__(environ, start_response)

WSGIServlet instances are WSGI applications by virtue of the implementation of this method which adheres to the protocol specified in PEP 3333.

Parameters:
  • environ – the WSGI environment.
  • start_response – the start response callable.
Return type:

an instance of wsgiservlets.HTTPResponse which are iterable.

The implementation is simple in principle and follows these steps:

  1. cache environ as environ

  2. create response as an instance of wsgiservlets.HTTPOK

  3. call, in order:
    1. _pre_lifecycle()
    2. _lifecycle()
    3. _post_lifecycle()
  4. return response

_pre_lifecycle()

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).

_lifecycle()

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.

_post_lifecycle()

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).

auth_realm

Specifies the realm for basic HTTP authentication. Default: 'Unspecified'.

use_form

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.

form

See use_form.

use_session

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.

session

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

session_config

A mapping holding session configuration variables. At this time there are two variables:

  1. timeout (default: 1800) The amount of time, in seconds, before a session times out.
  2. 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.
session_backend

Specifies the type of session to use. Currently, only one kind of session is in the distribution: FileSessionBackend.

session_backend_init

Session backend configuration, which is backend specific. For FileSessionBackend the only variable is:

  1. cachedir (default: /tmp/wsgisrv_sess) which specifies the root directory for session storage.
cookieclass

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.

method

Same as environ['REQUEST_METHOD']

script_name

Same as environ['SCRIPT_NAME']

path_info

Same as environ['PATH_INFO']

query_string

Same as environ['QUERY_STRING']

debug

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.

gen500msg

Terse message sent to clients on status 500 responses.

environ

The WSGI environment.

response

The response object, an instance of HTTPResponse.

http_headers

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:
   ...
path_info_list

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.

pop_path_info(count=1)

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”
cookies

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:
  • name – the name of the cookie.
  • value – its value.
  • cookieclass – the class used to create the cookie. If None, uses the class defined by cookieclass.
  • attrs – key/value pairs used to set attributes of the cookie. E.g., expires=3600.

Deletes a cookie.

Implemented by expiring the cookie; also sets the value to the empty string.

auth_with_mapping(mapping)

Helper method used in HTTP Basic Authentication.

Parameters:
  • mapping – any mapping that supports the standard dict.get() method, where the keys are usernames and their values passwords.

If the HTTP Authentication header does not have a username/password pair that is found in mapping unauthorized() is called.

get_basic_auth()

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).

unauthorized()

Helper method used in HTTP Basic Authentication.

Writes appropriate HTTP headers requesting authentication and raises HTTPUnauthorized exception. This method does not return.

redirect(uri, permanently=False)

Send a redirect to the client.

Parameters:
  • uri – The URI to relocate to.
  • permanently – If False (the default) reply with 307, Moved Temporarily, else 301, Moved Permanently.

This method does not return.

subrequest(wsgiservlet, environ=None)

Redirect internally.

This does not send a redirect to the client (see redirect()), but issues a subrequest to another servlet within the server.

Parameters:
  • wsgiservlet – The servlet instance to pass control to.
  • environ – If None (the default), a copy of self.environ will be used in the subrequest. If a mapping, it will be merged into a copy of self.environ and used in the subrequest.

Note

For subrequests, "wsgiservlets.subrequest" will be found in the environment with value True.

This method does not return.

log(msg)

Utility method to write a message to the error log, envrion['wsgi.errors'].

Parameters:
  • msg (str) – The message to be written to the log.
write(*args)

Utility method to write the arguments to the client.

Parameters:
  • args – tuple of arbitrary objects which will be converted to strings.
writeln(*args)

Like write(), but also append a newline.

Parameters:
  • args – tuple of arbitrary objects which will be converted to strings.
format_environ(sep='n')

Return the enivornment formatted: key=val SEP key=val SEP ...

Parameters:
  • sep – the separation string inserted between key=value paris. Default: newline.
http_time(timestamp=None)

Return the current date and time formatted for a message header.

send_file(path)

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.

classmethod test_server(servlet_class, host='', port=8000, forever=True, *args, **kw)

Create a test server.

Parameters:
  • host (str) – the host to bind the server. An empty string (the default) binds to all interfaces.
  • port (int) – the port to bind the server. The default is 8000.
  • forever (bool) – when True (the default) listen for connections forever; when False accept one connection then exit.
  • args,kw – passed to servlet constructor when creating an instance.

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/.

Previous topic

WSGIServlets Documentation

Next topic

wsgiservlets.HTMLPage

This Page