uw.web.wsgi package

Submodules

uw.web.wsgi.authority module

Automatic permissions checking.

Provides a function which delegates to an inner handler, first checking that access is allowed for the user and reporting an HTTP 403 if not.

uw.web.wsgi.authority.check_authority(check, handler)[source]

Delegate to an inner handler after checking permissions.

Parameters:

check – authority checking function; handler – inner handler to invoke assuming check passes.

Returns a WSGI handler which calls check(), passing the environment and the parameters. If the result is True, it chains to handler, otherwise it reports an HTTP 403 Forbidden error.

uw.web.wsgi.delegate module

URL path splitting and delegation support.

This module provides support for selecting a request handler based on an arc of the path component of the URL. A very flexible basic implementation is provided along with several more specific implementations for common uses.

Additionally, there is support for delegating based on the request method and in particular for the most common case of sending GET requests to one handler and POST requests to another handler.

class uw.web.wsgi.delegate.DelegateHandler[source]

Bases: object

Common superclass for WSGI handlers which delegate to other handlers.

This class is callable, and implements the WSGI interface.

Subclasses must define get_handler (environ) which determines the handler to which this handler will delegate handling of the request, and also updates environ appropriately.

class uw.web.wsgi.delegate.DelegateMethod(handler_dict)[source]

Bases: uw.web.wsgi.delegate.DelegateHandler

Delegate to an inner handler based on the HTTP method.

Takes a dictionary mapping HTTP methods to handlers. If the requested method is not in the dictionary, automatically raises a 405 Method Not Allowed HTTP Error.

get_handler(environ)[source]
property handler_dict
class uw.web.wsgi.delegate.DelegatePathArc(dir_handler, file_handler, convert_arc=None, save_arc=None, get_arc_handler=None)[source]

Bases: uw.web.wsgi.delegate.DelegateHandler

Class for WSGI handlers which delegate based on a URL path arc.

Parameters
  • dir_handler – The handler for requests with a slash ‘/’ at the end.

  • file_handler – The handler for requests without a slash ‘/’ at the end.

  • get_arc_handler(arc_object,**params) – get the handler for a path with an arc that translates to arc_object.

  • convert_arc(arc,**params) – convert the raw arc value into an object.

  • save_arc(arc_object,environ) – modify environ to store the arc_object in the appropriate way.

property convert_arc
property dir_handler
property file_handler
property get_arc_handler
get_handler(environ)[source]

Get the handler which will be used to handle the specified request.

The environ is the environ WSGI parameter. It is updated as when actually handling the request.

property save_arc
uw.web.wsgi.delegate.always(handler)[source]

Simplest get_arc_handler choice - choose a constant handler.

Parameters

handler – the WSGI handler to which to delegate all requests.

This function applied to a handler is typically passed to the get_arc_handler of delegate_value and is intended primarily for use with handlers resulting from that function.

The result of this function simply returns the specified handler, regardless of the URL path arc or the context.

uw.web.wsgi.delegate.date_delegate(index_handler, year_handler=None, month_handler=None, day_handler=None, prefix=None)[source]

Parse dates out of URL structure and delegate to year/month/day handlers.

Parameters
  • index_handler – the handler for the root /.

  • year_handler – the handler for /YYYY/.

  • month_handler – the handler for /YYYY/MM/.

  • day_handler – the handler for /YYYY/MM/DD/.

  • prefix – prefix to use for storing dates in the context.

Constructs WSGI handlers which analyze a date included in the URL. Requests for the root of the portion of the application handled by this handler are delegated to index_handler. Requests containing just a year number are delegated to year_handler. Requests containing just a year and month are delegated to month_handler. Requests containing a full date are delegated to day_handler.

The structure can be truncated by leaving some of the later parameters as None. To delegate only based on year, leave month_handler and day_handler as None; to delegate only to months leave day_handler as None.

uw.web.wsgi.delegate.delegate_action(dir_handler, handler_dict, file_handler=<function file_dir_redirect>)[source]

Delegate to a handler for a specific action based on the arc value.

Parameters
  • dir_handler – the handler to use when no (remaining) URL path arcs are present and the URL is a directory URL (ending in ‘/’).

  • handler_dict – a dictionary from URL path arc values to handlers.

  • file_handler – the handler to use when no (remaining) URL path arcs are present and the URL is a file URL (not ending in ‘/’).

Looks up the arc value in the handler_dict and delegates to the corresponding handler, or serve a 404 if not found.

uw.web.wsgi.delegate.delegate_file_only(handler)[source]

Delegate only file requests to the provided handler.

All file requests with no path information are delegated to the provided handler. All other requests (directory URL or if there are additional URL path arcs) result in a 404 error.

uw.web.wsgi.delegate.delegate_get_post(get_handler=None, post_handler=None)[source]

Convenience procedure for most common use of DelegateMethod.

Parameters
  • get_handler – the handler to use for HTTP GET requests.

  • post_handler – the handler to use for HTTP POST requests.

It is frequently convenient to use this as a function decorator, in which case it has the effect of making the decorated handler function into a GET-only handler.

uw.web.wsgi.delegate.delegate_value(name, dir_handler, get_arc_handler, file_handler=<function file_dir_redirect>, convert_arc=None)[source]

Delegate to an inner handler, storing the arc in the parameters.

Parameters
  • name – the name under which the converted arc value should be stored in the context.

  • dir_handler – the handler to use when no (remaining) URL path arcs are present and the URL is a directory URL (ending in ‘/’).

  • get_arc_handler – a function that returns the handler to use when there are remaining URL path arcs.

  • file_handler – the handler to use when no (remaining) URL path arcs are present and the URL is a file URL (not ending in ‘/’).

  • convert_arc – a function which converts the next URL path arc into a value which gets stored in the context.

The arc value is converted into a parameter value and stored in the handler parameters under the provided name. Usually get_arc_handler should just be “always (h)” where h is the appropriate handler. The flexibility allowed by making this parameter a function rather than simply being the required handler allows for completely different handlers to be used depending on the URL path arc value. In practice this capability has tended not to be used with delegate_value.

uw.web.wsgi.delegate.file_dir_redirect(environ, start_response)[source]

WSGI handler to redirect file URL to corresponding directory URL.

This implements the standard web server behaviour of redirecting a URL without an ending ‘/’ that corresponds to a directory to the same URL with ‘/’ appended.

uw.web.wsgi.delegate.int_from_arc(arc, **params)
uw.web.wsgi.delegate.make_day_from_arc(arc, **params)
uw.web.wsgi.delegate.make_int_from_arc(width=1)[source]

Convert an integer expressed canonically as a string into an int.

This essentially wraps int(), converting ValueError (parsing errors) into None. Additionally, the input must be left-0-padded to the specified width, and if the input is wider than the specified width, it must not begin with a ‘0’. The combined effect of these rules ensures that each non-negative integer has exactly one acceptable representation. Anything that has the wrong number of leading zeroes or which does not parse as an integer will return None.

uw.web.wsgi.delegate.make_month_from_arc(arc, **params)
uw.web.wsgi.delegate.make_year_from_arc(arc, **params)

uw.web.wsgi.demo module

Support for application demonstration versions.

This module allows creating a version of an application in which the user can pretend to be any user by specifying the userid as an arc of the URL. This is meant to support the creation of demonstration versions of applications.

class uw.web.wsgi.demo.File404(handler)[source]

Bases: uw.web.wsgi.delegate.DelegateHandler

Wrap a handler; return a 404 for file accesses, otherwise chain.

If the incoming request has (non-empty) PATH_INFO, chain to the provided handler, otherwise chain to no handler (resulting in 404).

get_handler(environ)[source]
uw.web.wsgi.demo.arc_handler(handler)[source]

Selectively replace the usual file_dir_redirect behaviour with 404.

Some web browsers automatically request /favicon.ico and possibly other URLs, which in a demo context results in a redirect to /favicon.ico/, leading to error messages when favicon.ico is not the userid of any identity. This replaces the initial response with a 404 instead.

uw.web.wsgi.demo.delegate_demo(handler)[source]

Obtain a userid-impersonation handler for demonstration purposes.

Parameters:

handler – the inner WSGI handler.

The resulting handler dispatches arc requests to the provided handler. The arc value is saved in the environment as the $REMOTE_USER variable used to determine the identity of the remote user. This is useful only when creating demos in order to allow any user to see and do what other users are able to do. Use of this handler completely defeats any authorization checking the contained handler may do.

uw.web.wsgi.errors module

HTTP status code reporting.

A WSGI handler which delegates to a wrapped handler. If the wrapped handler does not throw an HTTP status exception, then the wrapped handler is responsible for producing the WSGI response. Alternately, the wrapped handler may throw an HTTP status exception, in which case the handler in this module will produce an appropriate HTTP result based on the HTTP status.

uw.web.wsgi.errors.handle_errors(handler, error_handler=<uw.web.wsgi.parameter.ParamHandler object>)[source]

Return a WSGI handler to report error exceptions as HTTP errors.

Parameters:

handler – inner handler to invoke first; error_handler – handler to invoke in case an HTTP error is raised.

This function computes a WSGI handler. The returned handler first invokes handler, returning its result if it completes successfully.

If the inner handler fails with an HTTP error, the exception is stored in the context and error_handler is invoked. By default error_handler is simple_error_handler which produces a simple HTML document determined by the exception.

If the inner handler returns an HTTP status, also represented as an exception, a response with no body is produced. This is useful for HTTP redirects.

If an exception occurs that is not defined in the status module, it propagates without being caught. If this can happen, it may be appropriate to catch the exception and instead raise an HTTP Internal Server Error.

uw.web.wsgi.form module

HTML form result handling.

Routines for easily creating WSGI handlers which handle HTML form results.

class uw.web.wsgi.form.CGIFormResults(cgi_fields)[source]

Bases: dict

A representation of the form results component of a CGI request.

Parameters

cgi_fields (cgi.FieldStorage) – The values to be inserted into this form results dictionary.

multiple_field(name)[source]

Obtain a multiple field from the CGI results.

Parameters

name – the name of the field.

Return a list of all results for the named field.

multiple_field_value(name)[source]

Obtain multiple field values from the CGI results.

Parameters

name – the name of the field.

Return a list of the values of all the results for the named field.

optional_field(name)[source]

Obtain an optional field from the CGI results.

Parameters

name – the name of the field.

Return the single result for the named field, or None if there are none. If there are multiple results, an exception will be raised.

optional_field_value(name)[source]

Obtain an optional field value from the CGI results.

Parameters

name – the name of the field.

Return the value of the single result for the named field, or None if there are none. If there are multiple results, an exception will be raised.

required_field(name)[source]

Obtain a required field from the CGI results.

Parameters

name – the name of the field.

Return the single result for the named field, or raise an exception if there are none. If there are multiple results, an exception will be raised.

required_field_value(name)[source]

Obtain a required field value from the CGI results.

Parameters

name – the name of the field.

Return the value of the single result for the named field, or raise an exception if there are none. If there are multiple results, an exception will be raised.

class uw.web.wsgi.form.DelegateField(page_handler, get_form_handler, fields)[source]

Bases: uw.web.wsgi.delegate.DelegateHandler

Delegate to an inner handler based on a CGI field value.

Parameters
  • page_handler – The handler for requests with none of the specified fields present.

  • get_form_handler(**field_values) – The handler for requests with the given values for the specified fields.

  • fields – A dictionary from field names to the procedure to use to extract the field value from the CGIFormResults form value. Typical values include CGIFormResults.optional_field_value and friends.

property fields
property get_form_handler
get_handler(environ)[source]

Get the handler which will be used to handle the specified request.

property page_handler
uw.web.wsgi.form.get_form_fields(environ)[source]

Extract submitted HTML form results from the WSGI environment.

Parameters

environ – the WSGI environment.

Builds a CGIFormResults from the wsgi.input environment entry.

uw.web.wsgi.form.parse_form_value(value, parser)[source]

Parse a form value in a way that is usually appropriate.

Parameters
  • value – the string value, typically obtained from the form results.

  • parser – the parser to convert a non-empty string into a typed result.

The value may be None or a string. If it is None or a blank string then None is returned. Otherwise the value, stripped of leading and trailing whitespace, is passed to the parser and the result returned.

Typically parsers include the standard float and int functions.

uw.web.wsgi.form.use_form_param(handler)[source]

Wrap a hander; extract form variable values as a parameter.

Returns a handler which constructs a CGIFormResults dictionary and save it in the ‘form’ parameter before chaining to the provided handler.

uw.web.wsgi.function module

Support for creating WSGI handlers from functions.

This module makes it easy to create a WSGI handler whose implementation is a function with a convenient signature. The function body does not need to deal with the WSGI interface directly but can instead accept parameters corresponding to whatever information it needs from the request and return a result which is a data structure representing the HTML page to be rendered.

There are also routines making it easy to create handlers which return PDF, ZIP, CSV, or text files.

class uw.web.wsgi.function.FinalHandler(handler, convert, use_set_status=False, use_add_header=False)[source]

Bases: object

A handler class to create handlers with convenient signature.

This allows the body of a handler to be written as a function which takes parameter values extracted from the environment by a number of standard methods. The return value of the function can be converted into an actual CGI response by any desired conversion routine.

property convert

The result conversion routine.

This converts the result of the handler function into a proper return value for a WSGI handler.

property handler

The handler function.

Note that this is NOT a WSGI handler. Instead the parameters it expects are determined by the parameters expected to be set by previous handlers in the handler chain.

property use_add_header

Whether the handler function needs to add HTTP headers.

property use_set_status

Whether the handler function needs to set the HTTP status.

uw.web.wsgi.function.header_content_disposition(filename=None)[source]
uw.web.wsgi.function.return_csv(handler, encoding='utf-8', use_set_status=False, use_add_header=False)[source]

A FinalHandler subclass for returning a CSV file.

The handler implementation is expected to return a 2-tuple consisting of the .csv file content text and filename. The HTTP response sets the Content-Length header to the length of the encoded .csv file contents.

uw.web.wsgi.function.return_html(handler, encoding='utf-8', use_set_status=False, use_add_header=False)[source]

A FinalHandler subclass for returning HTML using a template.

The handler implementation is expected to return a 2-tuple consisting of the page title and the page contents. The final response is obtained by passing the results through a template found in the ‘template’ environment entry and converting the result to bytes using the specified encoding.

This is meant to work with the ll.xist XML/HTML library.

uw.web.wsgi.function.return_html_template(handler, template)[source]
uw.web.wsgi.function.return_json(handler, encoding='utf-8', use_set_status=False, use_add_header=False)[source]

A FinalHandler subclass for returning a JSON result.

The handler implementation is expected to return an object that can be written as JSON using json.dumps().

uw.web.wsgi.function.return_pdf(handler, use_set_status=False, use_add_header=False)[source]

A FinalHandler subclass for returning a PDF file.

The handler implementation is expected to return a 2-tuple consisting of the PDF file content bytes and filename. The HTTP response sets the Content-Length header to the length of the PDF file contents.

uw.web.wsgi.function.return_png(handler, use_set_status=False, use_add_header=False)[source]

A FinalHandler subclass for returning a PNG file.

The handler implementation is expected to return a 2-tuple consisting of the PNG file content bytes and filename. The HTTP response sets the Content-Length header to the length of the PNG file contents.

uw.web.wsgi.function.return_text(handler, encoding='utf-8', use_set_status=False, use_add_header=False)[source]

A FinalHandler subclass for returning a text file.

The handler implementation is expected to return just the file contents. The HTTP response sets the Content-Length header to the length of the text file contents once encoded as bytes.

uw.web.wsgi.function.return_text_download(handler, encoding='utf-8', use_set_status=False, use_add_header=False)[source]

A FinalHandler subclass for returning a text file as a download.

The handler implementation is expected to return the file contents and a suggested filename as which it should be saved. The HTTP response sets the Content-Length header to the length of the text file contents once encoded as bytes.

uw.web.wsgi.function.return_zip(handler, use_set_status=False, use_add_header=False)[source]

A FinalHandler subclass for returning a ZIP file.

The handler implementation is expected to return a 2-tuple consisting of the .zip file content bytes and filename. The HTTP response sets the Content-Length header to the length of the .zip file contents.

uw.web.wsgi.parameter module

Environment parameter support.

This module includes classes and procedures for building handlers which extract information from the Web request and store it in convenient form for use by a contained request handler.

class uw.web.wsgi.parameter.ParamHandler(handler, param_name, get_param_value)[source]

Bases: object

A chained handler class to store values in the parameters.

The constructor takes a nested handler, a parameter name param_name, and a parameter value extractor get_param_value. When the constructed handler is called, it extracts the parameter value from the environment using get_param_value and saves it in the parameters under the name param_name. Then it chains to the nested handler.

property get_param_value

The parameter calculator.

This is the function which computes the parameter value, given a CGI environment.

property handler

The nested handler.

This is the handler which is called when this handler is called after the parameter value has been stored in the parameters.

property param_name

The parameter name.

This is the name under which the parameter value is stored in the parameters.

uw.web.wsgi.parameter.get_cookies(environ)[source]

Get the cookie values from the provided CGI environment.

Creates a Cookie.SimpleCookie and loads it with the value of the HTTP_COOKIE environment variable.

uw.web.wsgi.parameter.get_form_fields(environ)[source]

Extract submitted HTML form results from the WSGI environment.

Parameters:

environ – the WSGI environment.

Builds a cgi.FieldStorage from the wsgi.input environment entry. Normally form.get_form_fields will be more useful than this function.

uw.web.wsgi.parameter.get_params(environ)[source]

Get the parameters from the provided CGI environment.

This simply returns the ‘params’ entry, or an empty dictionary if it is not present.

uw.web.wsgi.parameter.set_param(environ, name=None, value=None)[source]

Set a parameter value in the environment, or ensure presence.

If the environment does not contain a ‘params’ entry, it is created. If name is not None, then environ[‘params’][name] is set to value. It is an error for value to be not None if name is None.

uw.web.wsgi.parameter.use_cookies(handler)[source]

Wrap a handler; extract the cookies as a parameter.

Return a handler which stores the cookies from the HTTP_COOKIE environment entry in a Cookie.SimpleCookie object before chaining to the provided handler.

uw.web.wsgi.parameter.use_environ_param(handler)[source]

Wrap a handler; extract the environment as a parameter.

Returns a handler which saves the environment itself in the ‘environ’ parameter before chaining to the provided handler.

uw.web.wsgi.parameter.use_form_param(handler)[source]

Wrap a handler; extract form variable values as a parameter.

Returns a handler which constructs a cgi.FieldStorage and saves it in the ‘form’ parameter before chaining to the provided handler.

It is probably more useful to use form.use_form_param instead.

uw.web.wsgi.parameter.use_remote_user_param(handler)[source]

Wrap a handler; extract $REMOTE_USER as a parameter.

Returns a handler which saves the remote user in the ‘remote_user’ parameter before chaining to the provided handler.

uw.web.wsgi.parameter.use_request_uri_param(handler, include_query=False)[source]

Wrap a handler; extract request URI as a parameter.

Returns a handler which stores the request URI in the ‘request_uri’ parameter before chaining to the provided handler. By default the query string is not included.

uw.web.wsgi.sql module

Support for RDBMS sessions.

This module allows wrapping an application handler so that an SQL connection is automatically opened before handling the request, and committed afterward.

uw.web.wsgi.sql.sql_db(handler, db)[source]
uw.web.wsgi.sql.sql_pool_transaction(handler, connection_pool)[source]
uw.web.wsgi.sql.sql_transaction(handler)[source]

uw.web.wsgi.status module

HTTP status reporting.

This module provides classes corresponding to the various HTTP redirection and error codes. A typical page handler can report an HTTP status (other than the regular “200 OK”) by raising an instance of one of these classes.

exception uw.web.wsgi.status.HTTPBadRequest[source]

Bases: uw.web.wsgi.status.HTTPClientError

static handler(environ, start_response)[source]
exception uw.web.wsgi.status.HTTPClientError(status, description, body=None)[source]

Bases: uw.web.wsgi.status.HTTPError

HTTP client error status codes (4xx).

exception uw.web.wsgi.status.HTTPError(status, description, body=None)[source]

Bases: uw.web.wsgi.status.HTTPStatus

HTTP error status codes (4xx, 5xx).

exception uw.web.wsgi.status.HTTPForbidden[source]

Bases: uw.web.wsgi.status.HTTPClientError

static handler(environ, start_response)[source]
exception uw.web.wsgi.status.HTTPFound(url)[source]

Bases: uw.web.wsgi.status.HTTPRedirection

exception uw.web.wsgi.status.HTTPGone[source]

Bases: uw.web.wsgi.status.HTTPClientError

static handler(environ, start_response)[source]
exception uw.web.wsgi.status.HTTPInternalServerError(body=None)[source]

Bases: uw.web.wsgi.status.HTTPServerError

exception uw.web.wsgi.status.HTTPMethodNotAllowed(methods)[source]

Bases: uw.web.wsgi.status.HTTPClientError

get_headers(environ)[source]
static handler(methods)[source]
property methods
exception uw.web.wsgi.status.HTTPMovedPermanently(url)[source]

Bases: uw.web.wsgi.status.HTTPRedirection

exception uw.web.wsgi.status.HTTPNotFound[source]

Bases: uw.web.wsgi.status.HTTPClientError

static handler(environ, start_response)[source]
exception uw.web.wsgi.status.HTTPRedirection(status, description, url)[source]

Bases: uw.web.wsgi.status.HTTPStatus

HTTP redirection status codes (3xx).

get_headers(environ)[source]
property url
exception uw.web.wsgi.status.HTTPSeeOther(url)[source]

Bases: uw.web.wsgi.status.HTTPRedirection

exception uw.web.wsgi.status.HTTPServerError(status, description, body=None)[source]

Bases: uw.web.wsgi.status.HTTPError

HTTP server error status codes (5xx).

exception uw.web.wsgi.status.HTTPStatus(status, description, body=None)[source]

Bases: Exception

Top-level class for HTTP status reporting.

property description
get_body()[source]
get_headers(environ)[source]
get_status()[source]
property status
exception uw.web.wsgi.status.HTTPTemporaryRedirect(url)[source]

Bases: uw.web.wsgi.status.HTTPRedirection

Module contents

WSGI support library.

This package includes routines for building Web applications using the Python standard Web Server Gateway Interface (WSGI). It works by providing ways to create individual pages as mini WSGI applications, then combine them together to make larger WSGI applications.