webapp2

WSGI app

class webapp2.WSGIApplication(routes=None, debug=False, config=None)[source]

A WSGI-compliant application.

request_class

Class used for the request object.

response_class

Class used for the response object.

request_context_class

Class used for the request context object.

router_class

Class used for the router object.

config_class

Class used for the configuration object.

debug

A general purpose flag to indicate development mode: if True, uncaught exceptions are raised instead of using HTTPInternalServerError.

router

A Router instance with all URIs registered for the application.

config

A Config instance with the application configuration.

registry

A dictionary to register objects used during the app lifetime.

error_handlers

A dictionary mapping HTTP error codes to callables to handle those HTTP exceptions. See handle_exception().

app

Active WSGIApplication instance. See set_globals().

request

Active Request instance. See set_globals().

active_instance

Same as app, for webapp compatibility. See set_globals().

allowed_methods

Allowed request methods.

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

Initializes the WSGI application.

Parameters:
  • routes – A sequence of Route instances or, for simple routes, tuples (regex, handler).
  • debug – True to enable debug mode, False otherwise.
  • config – A configuration dictionary for the application.
__call__(environ, start_response)[source]

Called by WSGI when a request comes in.

Parameters:
  • environ – A WSGI environment.
  • start_response – A callable accepting a status code, a list of headers and an optional exception context to start the response.
Returns:

An iterable with the response to return to the client.

set_globals(app=None, request=None)[source]

Registers the global variables for app and request.

If webapp2_extras.local is available the app and request class attributes are assigned to a proxy object that returns them using thread-local, making the application thread-safe. This can also be used in environments that don’t support threading.

If webapp2_extras.local is not available app and request will be assigned directly as class attributes. This should only be used in non-threaded environments (e.g., App Engine Python 2.5).

Parameters:
clear_globals()[source]

Clears global variables. See set_globals().

handle_exception(request, response, e)[source]

Handles a uncaught exception occurred in __call__().

Uncaught exceptions can be handled by error handlers registered in error_handlers. This is a dictionary that maps HTTP status codes to callables that will handle the corresponding error code. If the exception is not an HTTPException, the status code 500 is used.

The error handlers receive (request, response, exception) and can be a callable or a string in dotted notation to be lazily imported.

If no error handler is found, the exception is re-raised.

Based on idea from Flask.

Parameters:
  • request – A Request instance.
  • response – A Response instance.
  • e – The uncaught exception.
Returns:

The returned value from the error handler.

run(bare=False)[source]

Runs this WSGI-compliant application in a CGI environment.

This uses functions provided by google.appengine.ext.webapp.util, if available: run_bare_wsgi_app and run_wsgi_app.

Otherwise, it uses wsgiref.handlers.CGIHandler().run().

Parameters:
  • bare – If True, doesn’t add registered WSGI middleware: use run_bare_wsgi_app instead of run_wsgi_app.
get_response(*args, **kwargs)[source]

Creates a request and returns a response for this app.

This is a convenience for unit testing purposes. It receives parameters to build a request and calls the application, returning the resulting response:

class HelloHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello, world!')

app = webapp2.WSGIapplication([('/', HelloHandler)])

# Test the app, passing parameters to build a request.
response = app.get_response('/')
assert response.status_int == 200
assert response.body == 'Hello, world!'
Parameters:
  • args – Positional arguments to be passed to Request.blank().
  • kwargs – Keyword arguments to be passed to Request.blank().
Returns:

A Response object.

class webapp2.RequestContext(app, environ)[source]

Context for a single request.

The context is responsible for setting and cleaning global variables for a request.

__init__(app, environ)[source]

Initializes the request context.

Parameters:
  • app – An WSGIApplication instance.
  • environ – A WSGI environment dictionary.
__enter__()[source]

Enters the request context.

Returns:A tuple (request, response).
__exit__(exc_type, exc_value, traceback)[source]

Exits the request context.

This release the context locals except if an exception is caught in debug mode. In this case they are kept to be inspected.

URI routing

See also

Router and URI routing

class webapp2.Router(routes=None)[source]

A URI router used to match, dispatch and build URIs.

route_class

Class used when the route is set as a tuple.

__init__(routes=None)[source]

Initializes the router.

Parameters:
  • routes – A sequence of Route instances or, for simple routes, tuples (regex, handler).
add(route)[source]

Adds a route to this router.

Parameters:
  • route – A Route instance or, for simple routes, a tuple (regex, handler).
match(request)

Matches all routes against a request object.

The first one that matches is returned.

Parameters:
Returns:

A tuple (route, args, kwargs) if a route matched, or None.

Raises :

exc.HTTPNotFound if no route matched or exc.HTTPMethodNotAllowed if a route matched but the HTTP method was not allowed.

build(request, name, args, kwargs)

Returns a URI for a named Route.

Parameters:
  • request – The current Request object.
  • name – The route name.
  • args – Tuple of positional arguments to build the URI. All positional variables defined in the route must be passed and must conform to the format set in the route. Extra arguments are ignored.
  • kwargs

    Dictionary of keyword arguments to build the URI. All variables not set in the route default values must be passed and must conform to the format set in the route. Extra keywords are appended as a query string.

    A few keywords have special meaning:

    • _full: If True, builds an absolute URI.
    • _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:

An absolute or relative URI.

dispatch(request, response)

Dispatches a handler.

Parameters:
Raises :

exc.HTTPNotFound if no route matched or exc.HTTPMethodNotAllowed if a route matched but the HTTP method was not allowed.

Returns:

The returned value from the handler.

adapt(handler)

Adapts a handler for dispatching.

Because handlers use or implement different dispatching mechanisms, they can be wrapped to use a unified API for dispatching. This way webapp2 can support, for example, a RequestHandler class and function views or, for compatibility purposes, a webapp.RequestHandler class. The adapters follow the same router dispatching API but dispatch each handler type differently.

Parameters:
  • handler – A handler callable.
Returns:

A wrapped handler callable.

default_matcher(request)[source]

Matches all routes against a request object.

The first one that matches is returned.

Parameters:
Returns:

A tuple (route, args, kwargs) if a route matched, or None.

Raises :

exc.HTTPNotFound if no route matched or exc.HTTPMethodNotAllowed if a route matched but the HTTP method was not allowed.

default_builder(request, name, args, kwargs)[source]

Returns a URI for a named Route.

Parameters:
  • request – The current Request object.
  • name – The route name.
  • args – Tuple of positional arguments to build the URI. All positional variables defined in the route must be passed and must conform to the format set in the route. Extra arguments are ignored.
  • kwargs

    Dictionary of keyword arguments to build the URI. All variables not set in the route default values must be passed and must conform to the format set in the route. Extra keywords are appended as a query string.

    A few keywords have special meaning:

    • _full: If True, builds an absolute URI.
    • _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:

An absolute or relative URI.

default_dispatcher(request, response)[source]

Dispatches a handler.

Parameters:
Raises :

exc.HTTPNotFound if no route matched or exc.HTTPMethodNotAllowed if a route matched but the HTTP method was not allowed.

Returns:

The returned value from the handler.

default_adapter(handler)[source]

Adapts a handler for dispatching.

Because handlers use or implement different dispatching mechanisms, they can be wrapped to use a unified API for dispatching. This way webapp2 can support, for example, a RequestHandler class and function views or, for compatibility purposes, a webapp.RequestHandler class. The adapters follow the same router dispatching API but dispatch each handler type differently.

Parameters:
  • handler – A handler callable.
Returns:

A wrapped handler callable.

set_matcher(func)[source]

Sets the function called to match URIs.

Parameters:
  • func – A function that receives (router, request) and returns a tuple (route, args, kwargs) if any route matches, or raise exc.HTTPNotFound if no route matched or exc.HTTPMethodNotAllowed if a route matched but the HTTP method was not allowed.
set_builder(func)[source]

Sets the function called to build URIs.

Parameters:
  • func – A function that receives (router, request, name, args, kwargs) and returns a URI.
set_dispatcher(func)[source]

Sets the function called to dispatch the handler.

Parameters:
  • func – A function that receives (router, request, response) and returns the value returned by the dispatched handler.
set_adapter(func)[source]

Sets the function that adapts loaded handlers for dispatching.

Parameters:
  • func – A function that receives (router, handler) and returns a handler callable.
class webapp2.BaseRoute(template, handler=None, name=None, build_only=False)[source]

Interface for URI routes.

template

The regex template.

name

Route name, used to build URIs.

handler

The handler or string in dotted notation to be lazily imported.

handler_method

The custom handler method, if handler is a class.

handler_adapter

The handler, imported and ready for dispatching.

build_only

True if this route is only used for URI generation and never matches.

match(request)[source]

Matches all routes against a request object.

The first one that matches is returned.

Parameters:
Returns:

A tuple (route, args, kwargs) if a route matched, or None.

build(request, args, kwargs)[source]

Returns a URI for this route.

Parameters:
  • request – The current Request object.
  • args – Tuple of positional arguments to build the URI.
  • kwargs – Dictionary of keyword arguments to build the URI.
Returns:

An absolute or relative URI.

get_routes()[source]

Generator to get all routes from a route.

Yields :This route or all nested routes that it contains.
get_match_routes()[source]

Generator to get all routes that can be matched from a route.

Match routes must implement match().

Yields :This route or all nested routes that can be matched.
get_build_routes()[source]

Generator to get all routes that can be built from a route.

Build routes must implement build().

Yields :A tuple (name, route) for all nested routes that can be built.
class webapp2.SimpleRoute(template, handler=None, name=None, build_only=False)[source]

A route that is compatible with webapp’s routing mechanism.

URI building is not implemented as webapp has rudimentar support for it, and this is the most unknown webapp feature anyway.

__init__(template, handler=None, name=None, build_only=False)

Initializes this route.

Parameters:
  • template – A regex to be matched.
  • handler – A callable or string in dotted notation to be lazily imported, e.g., 'my.module.MyHandler' or 'my.module.my_function'.
  • name – The name of this route, used to build URIs based on it.
  • build_only – If True, this route never matches and is used only to build URIs.
match(request)[source]

Matches this route against the current request.

See also

BaseRoute.match().

class webapp2.Route(template, handler=None, name=None, defaults=None, build_only=False, handler_method=None, methods=None, schemes=None)[source]

A route definition that maps a URI path to a handler.

The initial concept was based on Another Do-It-Yourself Framework, by Ian Bicking.

__init__(template, handler=None, name=None, defaults=None, build_only=False, handler_method=None, methods=None, schemes=None)[source]

Initializes this route.

Parameters:
  • template

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

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

    The same template can mix parts with name, regular expression or both.

    If the name is set, the value of the matched regular expression is passed as keyword argument to the handler. Otherwise it is passed as positional argument.

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

    Note

    The handler only receives *args if no named variables are set. Otherwise, the handler only receives **kwargs. This allows you to set regular expressions that are not captured: just mix named and unnamed variables and the handler will only receive the named ones.

  • handler – A callable or string in dotted notation to be lazily imported, e.g., 'my.module.MyHandler' or 'my.module.my_function'. It is possible to define a method if the callable is a class, separating it by a colon: 'my.module.MyHandler:my_method'. This is a shortcut and has the same effect as defining the handler_method parameter.
  • name – The name of this route, used to build URIs based on it.
  • defaults – Default or extra keywords to be returned by this route. Values also present in the route variables are used to build the URI when they are missing.
  • build_only – If True, this route never matches and is used only to build URIs.
  • handler_method – The name of a custom handler method to be called, in case handler is a class. If not defined, the default behavior is to call the handler method correspondent to the HTTP request method in lower case (e.g., get(), post() etc).
  • methods – A sequence of HTTP methods. If set, the route will only match if the request method is allowed.
  • schemes – A sequence of URI schemes, e.g., ['http'] or ['https']. If set, the route will only match requests with these schemes.
match(request)[source]

Matches this route against the current request.

Raises :exc.HTTPMethodNotAllowed if the route defines methods and the request method isn’t allowed.

See also

BaseRoute.match().

build(request, args, kwargs)[source]

Returns a URI for this route.

See also

Router.build().

Configuration

See also

Config

class webapp2.Config(defaults=None)[source]

A simple configuration dictionary for the WSGIApplication.

load_config(key, default_values=None, user_values=None, required_keys=None)[source]

Returns a configuration for a given key.

This can be used by objects that define a default configuration. It will update the app configuration with the default values the first time it is requested, and mark the key as loaded.

Parameters:
  • key – A configuration key.
  • default_values – Default values defined by a module or class.
  • user_values – User values, used when an object can be initialized with configuration. This overrides the app configuration.
  • required_keys – Keys that can not be None.
Raises :

Exception, when a required key is not set or is None.

Request and Response

class webapp2.Request(environ, *args, **kwargs)[source]

Abstraction for an HTTP request.

Most extra methods and attributes are ported from webapp. Check the WebOb documentation for the ones not listed here.

app

A reference to the active WSGIApplication instance.

response

A reference to the active Response instance.

route

A reference to the matched Route.

route_args

The matched route positional arguments.

route_kwargs

The matched route keyword arguments.

registry

A dictionary to register objects used during the request lifetime.

__init__(environ, *args, **kwargs)[source]

Constructs a Request object from a WSGI environment.

Parameters:
  • environ – A WSGI-compliant environment dictionary.
get(argument_name, default_value='', allow_multiple=False)[source]

Returns the query or POST argument with the given name.

We parse the query string and POST payload lazily, so this will be a slower operation on the first call.

Parameters:
  • argument_name – The name of the query or POST argument.
  • default_value – The value to return if the given argument is not present.
  • allow_multiple – Return a list of values with the given name (deprecated).
Returns:

If allow_multiple is False (which it is by default), we return the first value with the given name given in the request. If it is True, we always return a list.

get_all(argument_name, default_value=None)[source]

Returns a list of query or POST arguments with the given name.

We parse the query string and POST payload lazily, so this will be a slower operation on the first call.

Parameters:
  • argument_name – The name of the query or POST argument.
  • default_value – The value to return if the given argument is not present, None may not be used as a default, if it is then an empty list will be returned instead.
Returns:

A (possibly empty) list of values.

arguments()[source]

Returns a list of the arguments provided in the query and/or POST.

The return value is a list of strings.

get_range(name, min_value=None, max_value=None, default=0)[source]

Parses the given int argument, limiting it to the given range.

Parameters:
  • name – The name of the argument.
  • min_value – The minimum int value of the argument (if any).
  • max_value – The maximum int value of the argument (if any).
  • default – The default value of the argument if it is not given.
Returns:

An int within the given range for the argument.

class webapp2.Response(*args, **kwargs)[source]

Abstraction for an HTTP response.

Most extra methods and attributes are ported from webapp. Check the WebOb documentation for the ones not listed here.

Differences from webapp.Response:

  • out is not a StringIO.StringIO instance. Instead it is the response itself, as it has the method write().
  • As in WebOb, status is the code plus message, e.g., ‘200 OK’, while in webapp it is the integer code. The status code as an integer is available in status_int, and the status message is available in status_message.
  • response.headers raises an exception when a key that doesn’t exist is accessed or deleted, differently from wsgiref.headers.Headers.
__init__(*args, **kwargs)[source]

Constructs a response with the default settings.

status

The status string, including code and message.

status_message

The response status message, as a string.

has_error()[source]

Indicates whether the response was an error response.

clear()[source]

Clears all data written to the output stream so that it is empty.

wsgi_write(start_response)[source]

Writes this response using using the given WSGI function.

This is only here for compatibility with webapp.WSGIApplication.

Parameters:
  • start_response – The WSGI-compatible start_response function.
static http_status_message(code)[source]

Returns the default HTTP status message for the given code.

Parameters:
  • code – The HTTP code for which we want a message.

Request handlers

See also

Request handlers

class webapp2.RequestHandler(request=None, response=None)[source]

Base HTTP request handler.

Implements most of webapp.RequestHandler interface.

app

A WSGIApplication instance.

request

A Request instance.

response

A Response instance.

__init__(request=None, response=None)[source]

Initializes this request handler with the given WSGI application, Request and Response.

When instantiated by webapp.WSGIApplication, request and response are not set on instantiation. Instead, initialize() is called right after the handler is created to set them.

Also in webapp dispatching is done by the WSGI app, while webapp2 does it here to allow more flexibility in extended classes: handlers can wrap dispatch() to check for conditions before executing the requested method and/or post-process the response.

Note

Parameters are optional only to support webapp’s constructor which doesn’t take any arguments. Consider them as required.

Parameters:
initialize(request, response)[source]

Initializes this request handler with the given WSGI application, Request and Response.

Parameters:
dispatch()[source]

Dispatches the request.

This will first check if there’s a handler_method defined in the matched route, and if not it’ll use the method correspondent to the request method (get(), post() etc).

error(code)[source]

Clears the response and sets the given HTTP status code.

This doesn’t stop code execution; for this, use abort().

Parameters:
  • code – HTTP status error code (e.g., 501).
abort(code, *args, **kwargs)[source]

Raises an HTTPException.

This stops code execution, leaving the HTTP exception to be handled by an exception handler.

Parameters:
  • code – HTTP status code (e.g., 404).
  • args – Positional arguments to be passed to the exception class.
  • kwargs – Keyword arguments to be passed to the exception class.
redirect(uri, permanent=False, abort=False, code=None, body=None)[source]

Issues an HTTP redirect to the given relative URI.

The arguments are described in redirect().

redirect_to(_name, _permanent=False, _abort=False, _code=None, _body=None, *args, **kwargs)[source]

Convenience method mixing redirect() and uri_for().

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

uri_for(_name, *args, **kwargs)[source]

Returns a URI for a named Route.

See also

Router.build().

handle_exception(exception, debug)[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.
  • debug_mode – True if the web application is running in debug mode.
class webapp2.RedirectHandler(request=None, response=None)[source]

Redirects to the given URI for all GET requests.

This is intended to be used when defining URI routes. You must provide at least the keyword argument url in the route default values. Example:

def get_redirect_url(handler, *args, **kwargs):
    return handler.uri_for('new-route-name')

app = WSGIApplication([
    Route('/old-url', RedirectHandler, defaults={'_uri': '/new-url'}),
    Route('/other-old-url', RedirectHandler, defaults={
          '_uri': get_redirect_url}),
])

Based on idea from Tornado.

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

Performs a redirect.

Two keyword arguments can be passed through the URI route:

  • _uri: A URI string or a callable that returns a URI. The callable is called passing (handler, *args, **kwargs) as arguments.
  • _code: The redirect status code. Default is 301 (permanent redirect).

Utilities

These are some other utilities also available for general use.

class webapp2.cached_property(func, name=None, doc=None)[source]

A decorator that converts a function into a lazy property.

The function wrapped is called the first time to retrieve the result and then that calculated result is used the next time you access the value:

class Foo(object):

    @cached_property
    def foo(self):
        # calculate something important here
        return 42

The class has to have a __dict__ in order for this property to work.

Note

Implementation detail: this property is implemented as non-data descriptor. non-data descriptors are only invoked if there is no entry with the same name in the instance’s __dict__. this allows us to completely get rid of the access function call overhead. If one choses to invoke __get__ by hand the property will still work as expected because the lookup logic is replicated in __get__ for manual invocation.

This class was ported from Werkzeug and Flask.

webapp2.get_app()[source]

Returns the active app instance.

Returns:A WSGIApplication instance.
webapp2.get_request()[source]

Returns the active request instance.

Returns:A Request instance.
webapp2.redirect(uri, permanent=False, abort=False, code=None, body=None, request=None, response=None)[source]

Issues an HTTP redirect to the given relative URI.

This won’t stop code execution unless abort is True. A common practice is to return when calling this method:

return redirect('/some-path')
Parameters:
  • uri – A relative or absolute URI (e.g., '../flowers.html').
  • permanent – If True, uses a 301 redirect instead of a 302 redirect.
  • abort – If True, raises an exception to perform the 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.
  • request – Optional request object. If not set, uses get_request().
  • response – Optional response object. If not set, a new response is created.
Returns:

A Response instance.

webapp2.redirect_to(_name, _permanent=False, _abort=False, _code=None, _body=None, _request=None, _response=None, *args, **kwargs)[source]

Convenience function mixing redirect() and uri_for().

Issues an HTTP redirect to a named URI built using uri_for().

Parameters:
  • _name – The route name to redirect to.
  • args – Positional arguments to build the URI.
  • kwargs – Keyword arguments to build the URI.
Returns:

A Response instance.

The other arguments are described in redirect().

webapp2.uri_for(_name, _request=None, *args, **kwargs)[source]

A standalone uri_for version that can be passed to templates.

See also

Router.build().

webapp2.abort(code, *args, **kwargs)[source]

Raises an HTTPException.

Parameters:
  • code – An integer that represents a valid HTTP status code.
  • args – Positional arguments to instantiate the exception.
  • kwargs – Keyword arguments to instantiate the exception.
webapp2.import_string(import_name, silent=False)[source]

Imports an object based on a string in dotted notation.

Simplified version of the function with same name from Werkzeug.

Parameters:
  • import_name – String in dotted notation of the object to be imported.
  • silent – If True, import or attribute errors are ignored and None is returned instead of raising an exception.
Returns:

The imported object.