Modules

wheezy.http

wheezy.http.application

application module.

class wheezy.http.application.WSGIApplication(middleware, options)[source]

The application object is simply a WSGI callable object.

middleware is any callable of the following contract:

def middleware(request, following):
    if following:
        response = following(request)
    else:
        response
    return response

middleware_factory is a factory that initialize middleware:

def middleware_factory(options):
    return middleware

middleware_factory can return None, this can be useful for some sort of initialization that needs to be run during application bootstrap.

wheezy.http.application.wrap_middleware(following, func)[source]

Helper function to wrap middleware, adapts middleware contract to:

def handler(request):
    return response

following - next middleware in the chain. func - middleware callable.

wheezy.http.authorization

wheezy.http.authorization.secure(wrapped=None, enabled=True)[source]

Checks if user is accessing protected resource via SSL and if not, issue permanent redirect to HTTPS location.

enabled - whenever to do any checks (defaults to True).

Example:

@secure
def my_view(request):
    ...
    return response

Using enabled:

@secure(enabled=False)
def my_view(request):
    ...
    return response

wheezy.http.cache

cache module

class wheezy.http.cache.CacheableResponse(response)[source]

Cachable response.

class wheezy.http.cache.NotModifiedResponse(response)[source]

Not modified cachable response.

class wheezy.http.cache.SurfaceResponse(response)[source]

WSGI wrapper that returns response headers and buffer.

wheezy.http.cache.make_etag(hasher)[source]

Build etag function based on hasher algorithm.

wheezy.http.cache.make_etag_crc32(hasher)[source]

Build etag function based on hasher algorithm and crc32.

wheezy.http.cache.response_cache(profile=None)[source]

Decorator that applies cache profile strategy to the wrapping handler.

wheezy.http.cache.wsgi_cache(profile)[source]

Decorator that wraps wsgi app and set cache profile.

wheezy.http.cachepolicy

cachepolicy module.

class wheezy.http.cachepolicy.HTTPCachePolicy(cacheability='private')[source]

Controls cache specific http headers.

append_extension(extension)[source]

Appends the extension to the Cache-Control HTTP header.

etag(tag)[source]

Provides the current value of the entity tag for the requested variant.

Not valid for no-cache cacheability, raise AssertionError.

expires(when)[source]

The Expires entity-header field gives the date/time after which the response is considered stale.

Not valid for no-cache cacheability, raise AssertionError.

extend(headers)[source]

Updates headers with this cache policy.

http_cache_control()[source]

Returns a value for Cache-Control header.

http_vary()[source]

Returns a value for Vary header.

last_modified(when)[source]

The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified.

Not valid for no-cache cacheability, raise AssertionError.

max_age(delta)[source]

Accept a response whose age is no greater than the specified time in seconds.

delta can be int or datetime.timedelta.

Not valid for no-cache cacheability, raise AssertionError.

must_revalidate()[source]

Because a cache MAY be configured to ignore a server’s specified expiration time, and because a client request MAY include a max-stale directive (which has a similar effect), the protocol also includes a mechanism for the origin server to require revalidation of a cache entry on any subsequent use.

Raises AssertionError if proxy-revalidave is set.

no_cache(*fields)[source]

The specified field-name(s) MUST NOT be sent in the response to a subsequent request without successful revalidation with the origin server.

Not valid for no-cache cacheability.

no_store()[source]

The purpose of the no-store directive is to prevent the inadvertent release or retention of sensitive information.

no_transform()[source]

The cache or proxy MUST NOT change any aspect of the entity-body that is specified by this header, including the value of the entity-body itself.

private(*fields)[source]

Indicates that part of the response message is intended for a single user and MUST NOT be cached by a shared cache.

Only valid for public cacheability.

proxy_revalidate()[source]

The proxy-revalidate directive has the same meaning as the must- revalidate directive, except that it does not apply to non-shared user agent caches.

Raises AssertionError if must-revalidave is set.

smax_age(delta)[source]

If a response includes an s-maxage directive, then for a shared cache (but not for a private cache), the maximum age specified by this directive overrides the maximum age specified by either the max-age directive or the Expires header. Accept a response whose age is no greater than the specified time in seconds.

delta can be int or datetime.timedelta.

Not valid for no-cache cacheability, raise AssertionError.

vary(*headers)[source]

The Vary field value indicates the set of request-header fields that fully determines, while the response is fresh, whether a cache is permitted to use the response to reply to a subsequent request without revalidation.

Not valid for no-cache cacheability, raise AssertionError.

wheezy.http.cacheprofile

cacheprofile module.

class wheezy.http.cacheprofile.CacheProfile(location, duration=0, no_store=False, vary_query=None, vary_form=None, vary_environ=None, vary_cookies=None, http_vary=None, http_max_age=None, etag_func=None, namespace=None, enabled=True)[source]

Combines a number of setting applicable to http cache policy as well as server side cache.

cache_policy()[source]

Returns cache policy according to this cache profile. Defaults to None and substituted depending on profile strategy.

client_policy()[source]

Returns private or public http cache policy depending on cache profile selected.

class wheezy.http.cacheprofile.RequestVary(query=None, form=None, cookies=None, environ=None)[source]

Designed to compose a key depending on number of values, including: query, form, environ.

key(request)[source]

Key by various strategies.

key_cookies(request)[source]

Key by cookies.

key_environ(request)[source]

Key by environ.

key_form(request)[source]

Key by form.

key_query(request)[source]

Key by query.

request_key(request)[source]

Key by method and PATH_INFO.

wheezy.http.cacheprofile.utcfromtimestamp()

timestamp -> UTC datetime from a POSIX timestamp (like time.time()).

wheezy.http.config

config module.

wheezy.http.config.bootstrap_http_defaults(options)[source]

Bootstraps http default options.

def bootstrap_http_defaults(options):
    """ Bootstraps http default options.
    """
    options.setdefault('ENCODING', 'UTF-8')
    options.setdefault('MAX_CONTENT_LENGTH', 4 * 1024 * 1024)
    options.setdefault('HTTP_COOKIE_DOMAIN', None)
    options.setdefault('HTTP_COOKIE_SECURE', False)
    options.setdefault('HTTP_COOKIE_HTTPONLY', False)
    return None

wheezy.http.cookie

cookie module.

class wheezy.http.cookie.HTTPCookie(name, value=None, path='/', expires=None, max_age=None, domain=None, secure=None, httponly=None, options=None)[source]

HTTP Cookie http://www.ietf.org/rfc/rfc2109.txt

domain, secure and httponly are taken from config if not set.

classmethod delete(name, path='/', domain=None, options=None)[source]

Returns a cookie to be deleted by browser.

Returns Set-Cookie response header.

wheezy.http.functional

functional module.

class wheezy.http.functional.BenchmarkMixin[source]

Benchmark test case helper.

benchmark(targets, number=1000)[source]

Setup benchmark for given targets with timing set at WSGI application entry point.

class wheezy.http.functional.Form(attrs=None)[source]

Form class represent HTML form. It stores form tag attributes, params that can be used in form submission as well as related HTML elements.

class wheezy.http.functional.FormTarget[source]

FormTarget finds forms and elements like input, select, etc.

class wheezy.http.functional.PageMixin[source]

Page form submit use case.

ajax_submit(**kwargs)[source]

Submits page via AJAX with given kwargs as form params.

Returns HTTP status code.

form()[source]

Concrete page can override this method to provide form location.

submit(**kwargs)[source]

Submits page with given kwargs as form params.

Returns any form errors found. If form is not found returns None.

class wheezy.http.functional.WSGIClient(application, environ=None)[source]

WSGI client simulates WSGI requests in order to accomplish functional testing for any WSGI application.

ajax_get(path=None, **kwargs)[source]

Issue GET HTTP AJAX request to WSGI application.

ajax_post(path=None, **kwargs)[source]

Issue POST HTTP AJAX request to WSGI application.

ajax_submit(form=None, environ=None)[source]

Submits given form. Takes action and method form attributes into account.

build_environ(path=None, method='GET', params=None, environ=None, content_type='', stream=None, content='')[source]

Builds WSGI environment.

The content_type takes priority over params to use stream or content.

content None[source]

Return content of the response. Applies decodes response stream.

follow()[source]

Follows HTTP redirect (e.g. status code 302).

form None[source]

First form or empty one.

form_by(predicate=None, **kwargs)[source]

Search a form by predicate or form attribute exact match:

client.form_by(action='/en/signin')
client.form_by(lambda attrs:
               'signin' in attrs.get('action', ''))
forms None[source]

All forms found in content.

get(path=None, **kwargs)[source]

Issue GET HTTP request to WSGI application.

go(*args, **kwargs)[source]

Simulate valid request to WSGI application.

head(path=None, **kwargs)[source]

Issue HEAD HTTP request to WSGI application.

json None[source]

Returns a json response.

post(path=None, **kwargs)[source]

Issue POST HTTP request to WSGI application.

run(environ)[source]

Calls WSGI application with given environ.

submit(form=None, environ=None)[source]

Submits given form. Takes action and method form attributes into account.

wheezy.http.method

method module.

wheezy.http.method.accept_method(constraint)[source]

Decorator that accepts only particular HTTP request method if constraint is a string:

@accept_method('GET')
def my_view(request):
    response = ...
    return response

or HTTP request methods if constraint is a list or tuple:

@accept_method(('GET', 'POST'))
def my_view(request):
    response = ...
    return response

method constraint must be in uppercase.

wheezy.http.middleware

middleware module.

class wheezy.http.middleware.EnvironCacheAdapterMiddleware[source]

WSGI environ cache adapter middleware.

class wheezy.http.middleware.HTTPCacheMiddleware(cache, middleware_vary)[source]

HTTP cache middleware.

class wheezy.http.middleware.WSGIAdapterMiddleware(wsgi_app)[source]

WSGI adapter middleware.

wheezy.http.middleware.environ_cache_adapter_middleware_factory(options)[source]

WSGI environ cache adapter middleware factory.

wheezy.http.middleware.http_cache_middleware_factory(options)[source]

HTTP cache middleware factory.

Requires http_cache in options.

Supports http_cache_middleware_vary - a way to determine cache key for the request.

wheezy.http.middleware.wsgi_adapter_middleware_factory(options)[source]

WSGI adapter middleware factory.

Requires wsgi_app in options.

wheezy.http.parse

parser module.

Parse cookie string and return a dictionary where key is a name of the cookie and value is cookie value.

wheezy.http.parse.parse_multipart(fp, ctype, clength, encoding)[source]

Parse multipart/form-data request. Returns a tuple (form, files).

wheezy.http.request

request module.

class wheezy.http.request.HTTPRequest(environ, encoding, options)[source]

Represent HTTP request. environ variables are accessable via attributes.

load_body()[source]

Load http request body and returns form data and files.

wheezy.http.response

response module.

class wheezy.http.response.HTTPResponse(content_type='text/html; charset=UTF-8', encoding='UTF-8')[source]

HTTP response.

Response headers Content-Length and Cache-Control must not be set by user code directly. Use HTTPCachePolicy instead (HTTPResponse.cache).

get_status()[source]

Returns a string that describes the specified HTTP status code.

redirect(absolute_url, status_code=302)[source]

Redirect response to absolute_url and sets status_code.

status None

Returns a string that describes the specified HTTP status code.

write(chunk)[source]

Applies encoding to chunk and append it to response buffer.

write_bytes(chunk)[source]

Appends chunk it to response buffer. No special checks performed. It must be valid object for WSGI response.

wheezy.http.response.ajax_redirect(absolute_url)[source]

Shortcut function to return ajax redirect response.

Browsers incorrectly handle redirect response to ajax request, so we return status code 207 that javascript is capable to receive and process browser redirect.

Here is an example for jQuery:

$.ajax({
    // ...
    success: function(data, textStatus, jqXHR) {
        if (jqXHR.status == 207) {
            window.location.replace(
                jqXHR.getResponseHeader('Location'));
        } else {
            // ...
        }
    }
});
wheezy.http.response.found(absolute_url)

Shortcut function to return redirect response.

The HTTP response status code 302 Found is a common way of performing a redirection.

wheezy.http.response.http_error(status_code)[source]

Shortcut function to return a response with given status code.

wheezy.http.response.json_response(obj, encoding='UTF-8')[source]

Returns json response.

wheezy.http.response.permanent_redirect(absolute_url)[source]

Shortcut function to return permanent redirect response.

The HTTP response status code 301 Moved Permanently is used for permanent redirection.

wheezy.http.response.redirect(absolute_url)[source]

Shortcut function to return redirect response.

The HTTP response status code 302 Found is a common way of performing a redirection.

wheezy.http.response.see_other(absolute_url)[source]

Shortcut function to return see other redirect response.

The HTTP response status code 303 See Other is the correct manner in which to redirect web applications to a new URI, particularly after an HTTP POST has been performed.

This response indicates that the correct response can be found under a different URI and should be retrieved using a GET method. The specified URI is not a substitute reference for the original resource.

wheezy.http.response.temporary_redirect(absolute_url)[source]

Shortcut function to return temporary redirect response.

In this occasion, the request should be repeated with another URI, but future requests can still use the original URI. In contrast to 303, the request method should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.

wheezy.http.transforms

transforms module

wheezy.http.transforms.gzip_transform(compress_level=6, min_length=1024, vary=False)[source]

Allows gzip compression.

compress_level - the compression level, between 1 and 9, where 1 is the least compression (fastest) and 9 is the most (slowest)

min_length - sets the minimum length, in bytes, of the first chunk in response that will be compressed. Responses shorter than this byte-length will not be compressed.

vary - enables response header “Vary: Accept-Encoding”.

wheezy.http.transforms.response_transforms(*transforms)[source]

Applies several transforms at once.