Avalanche Python Web Framework with a focus on testability and reusability

Table Of Contents

Previous topic

Tutorial - Understanding Avalanche

Project links



API Reference

Request & Response

check webob docs

Routing

class avalanche.router.Route(template, endpoint, name=None)[source]

Route for URL paths

A route template to match against the request path. A template can have variables enclosed by <> that define a name, and and optional regular expression. Examples:

Format Example
<name> '/blog/<year>/<month>'
<name:regex> '/blog/<year:\d{4}>/<month:\d{2}>'

The value of the matched regular expression is passed as keyword argument to the handler.

If only the name is set, it will match anything except a slash. So these routes are equivalent:

Route('/<user_id>/settings', handler=SettingsHandler,
      name='user-settings')
Route('/<user_id:[^/]+>/settings', handler=SettingsHandler,
      name='user-settings')
__init__(template, endpoint, name=None)[source]
Parameters:
  • template – URL template string
  • endpoint – reference to request handler (or whatever)
  • name – (string) route name
build(**kwargs)[source]

build path for this route.

Parameters:kwargs – Dictionary of keyword arguments to build the URI.
Returns:(str) path
match(request)[source]

Check if request matches this route

Parameters:request – A request to be checked if matches the template
Returns:A dict kwargs if route matched, or None.
class avalanche.router.MatchResult

MatchResult(route, kwargs)

class avalanche.router.Router(*routes)[source]

A URI router used to match and build URIs.

__init__(*routes)[source]

Initializes the router.

Parameters:routes – A sequence of (Route, :str:name) instances
add(route)[source]

Adds a route to this router.

Parameters:route – A Route instance or, for simple routes, a tuple (regex, handler).
build(_name, **kwargs)[source]

Returns a URI for a named Route.

Parameters:
  • _name – The route name.
  • kwargs

    Dictionary of keyword arguments to build the URI. All variables values must be passed. Extra keywords are appended as a query string.

    A few keywords have special meaning:

    • _scheme: URI scheme, e.g., http or https. If defined, an absolute URI is always returned.
    • _netloc: Network location, e.g., www.google.com. If defined, an absolute URI is always returned.
    • _fragment: If set, appends a fragment (or “anchor”) to the generated URI.
Returns:

(string) An absolute or relative URI.

match(request)[source]

Matches all routes against a value

Returns:MatchResult or None if no route is matched

core.RequestHandler

class avalanche.core.RequestHandler(app, request)[source]

Base HTTP request handler - this should be subclassed

Attributes: app, request, response are references.

Subclasses should implement the handled HTTP methods (get, post, ...). The handler methods take *args, **kwargs from its route values.

Subclasses may overwrite the handle_exception method.

The methods redirect, uri_for and redirect_to are helpers to be used on handler methods.

The wsgi application executes the handler using the dispatch method. This can also be subclassed to add to some extra stuff.

__init__(app, request)[source]
Parameters:
  • app – (WSGIApplication)
  • request – (Request)
dispatch(*args, **kwargs)[source]

Execute the handler method (get, post, ...)

Sets the response attribute.

Parameters:
  • args – list of arguments to be passed to handler method
  • kwargs – dict of arguments to be passed to handler method
handle_exception(exception)[source]

Called if this handler throws an exception during execution.

The default behavior is to re-raise the exception to be handled by WSGIApplication._handle_exception().

Parameters:exception – The exception that was thrown.
redirect(uri, permanent=False, code=None, body=None)[source]

sets the response with HTTP redirect to the given relative URI.

Parameters:
  • uri – A relative or absolute URI (e.g., '../flowers.html').
  • permanent – If True, uses a 301 redirect instead of a 302 redirect.
  • code – The redirect status code. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with defined If-Modified-Since headers.
  • body – Response body, if any.
redirect_to(_name, _permanent=False, _code=None, _body=None, **kwargs)[source]

Convenience method mixing redirect() and uri_for().

The arguments are described in redirect() and uri_for().

uri_for(_name, **kwargs)[source]

Shortcut to build a URI from app router

see also avalanche.router.Router.build()

core.WSGIApplication

class avalanche.core.WSGIApplication(routes=(), debug=False, error_handlers=None)[source]

A WSGI application

__init__(routes=(), debug=False, error_handlers=None)[source]

Initializes the WSGI application.

Parameters:
  • routes – A sequence of Route instances
  • debug – True to enable debug mode, False otherwise. If value is (string) ‘pdb’ enables post-mortem debug using PDB on your terminal (if running on localhost only).
  • error_handlers – A dictionary mapping HTTP error codes (int) to RequestHandler’s
internal_error(exception)[source]

called when an iternal error occurs, logs the exception

this should be sub-classed to perform some extra operations on 500 typically used to send email to admin/developers

Renderers

Any object that implements that implements a render method. render method takes 2 parameters:

  • handler: a reference
  • context: a dictionary

Avalanche comes with a few renderers:

class avalanche.renderer.JinjaRenderer(jinja_env)[source]

render jinja2 templates

__init__(jinja_env)[source]
Parameters:jinja_env – instance of jinja2.Environment
render(handler, **context)[source]

Renders handler.template and writes the result to its response

class avalanche.renderer.JsonRenderer[source]

render json data

static render(handler, **context)[source]

write response to handler’s reponse

class avalanche.renderer.NoOpRenderer[source]

No operation renderer, to be used when handler writes no response

Avalanche Request Handlers

User’s should create handlers by subclassing BaseHandler.

make_handler result should be used on the WSGIApplication.

avalanche.__init__.make_handler(request_handler, app_handler, dict_=None)[source]

creates a concrete request handler => ApplicationHandler(avalanche.Handler) + _AvalancheHandler + core.RequestHandler

class avalanche.__init__._AvalancheHandler[source]

avalanche functionality.

Users should not subclass this directly, use make_handler

context_get = ['a_get']

list of context-builder method names used on GET requests

context_post = ['a_post']

list of context-builder method names used on POST requests

renderer = None

A renderer instance

template = None

(string) path to jinja template to be rendered

class avalanche.__init__.BaseHandler[source]

Base class that user should subclass when creating request handlers

classmethod set_config()[source]

used to modify config values inherited from a base class

config values are saved as a dict in the attribute ‘a_config’.

  • on first level keys are the name of config-builders
  • on second level keys are the parameter names
  • values are instances of AvalancheParam
class MyHandler(MyHandlerBase):
    @classmethod
    def set_config(cls):
        cls.a_config['builder_a']['x'] = avalanche.UrlQueryParam('x', 'x2')
class avalanche.__init__.AvaResponse[source]

base class for a returned value from a context builder that creates a response directly instead of a context dict

class avalanche.__init__.Redirect(uri)[source]
class avalanche.__init__.RedirectTo(handler_name, **kwargs)[source]

Context-builder parameter converter

class avalanche.params.AvalancheParam(obj_name)[source]

A parameter converter - (Abstract base class)

This is used to convert parameters (i.e. from the URL) from string to its real type.

Parameters:obj_name (str) – name of param to be passed to context_builders
get_value(request)[source]

return a value taken from request

avalanche.params.UrlPathParam(obj_name, str_name=None, str2obj=None)[source]

get parameter from URL path (given by route)

Parameters:
  • str_name (str) – name of param on the source if not provided use same as obj_name
  • str2obj

    callable that converts param string to an object if not provided obj it just returns the str_value there are 2 acceptable signatures for the callable:

    • take a single param with the str_value
    • first param takes str_value, second is named ‘handler’ and receives a reference to the RequestHandler
avalanche.params.UrlQueryParam(obj_name, str_name=None, str2obj=None)[source]

get parameter from the URL query string

avalanche.params.GetParam(obj_name)[source]

get a dictionary with all GET params”

avalanche.params.PostParam(obj_name)[source]

get a dictionary with all POST params”

avalanche.params.PostGroupParam(obj_name, str_name=None)[source]

get a dictionary with all paramaters which name starts with “<str_name>-“

avalanche.params.ContextParam(obj_name, str_name=None)[source]

get param from request-handler context