See also
A WSGI-compliant application.
Class used for the request object.
Class used for the response object.
Class used for the request context object.
Class used for the router object.
Class used for the configuration object.
A general purpose flag to indicate development mode: if True, uncaught exceptions are raised instead of using HTTPInternalServerError.
A dictionary to register objects used during the app lifetime.
A dictionary mapping HTTP error codes to callables to handle those HTTP exceptions. See handle_exception().
Active WSGIApplication instance. See set_globals().
Active Request instance. See set_globals().
Same as app, for webapp compatibility. See set_globals().
Allowed request methods.
Initializes the WSGI application.
| Parameters: |
|
|---|
Called by WSGI when a request comes in.
| Parameters: |
|
|---|---|
| Returns: | An iterable with the response to return to the client. |
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: |
|
|---|
Clears global variables. See set_globals().
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: | |
|---|---|
| Returns: | The returned value from the error handler. |
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: |
|
|---|
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: |
|
|---|---|
| Returns: | A Response object. |
Context for a single request.
The context is responsible for setting and cleaning global variables for a request.
Initializes the request context.
| Parameters: |
|
|---|
See also
Router and URI routing
A URI router used to match, dispatch and build URIs.
Class used when the route is set as a tuple.
Initializes the router.
| Parameters: |
|
|---|
Adds a route to this router.
| Parameters: |
|
|---|
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. |
Returns a URI for a named Route.
| Parameters: |
|
|---|---|
| Returns: | An absolute or relative URI. |
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. |
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: |
|
|---|---|
| Returns: | A wrapped handler callable. |
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. |
Returns a URI for a named Route.
| Parameters: |
|
|---|---|
| Returns: | An absolute or relative URI. |
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. |
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: |
|
|---|---|
| Returns: | A wrapped handler callable. |
Sets the function called to match URIs.
| Parameters: |
|
|---|
Sets the function called to build URIs.
| Parameters: |
|
|---|
Interface for URI routes.
The regex template.
Route name, used to build URIs.
The handler or string in dotted notation to be lazily imported.
The custom handler method, if handler is a class.
The handler, imported and ready for dispatching.
True if this route is only used for URI generation and never matches.
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. |
Returns a URI for this route.
| Parameters: |
|
|---|---|
| Returns: | An absolute or relative URI. |
Generator to get all routes from a route.
| Yields : | This route or all nested routes that it contains. |
|---|
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.
Initializes this route.
| Parameters: |
|
|---|
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.
Initializes this route.
| Parameters: |
|
|---|
Matches this route against the current request.
| Raises : | exc.HTTPMethodNotAllowed if the route defines methods and the request method isn’t allowed. |
|---|
See also
See also
A simple configuration dictionary for the WSGIApplication.
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: |
|
|---|---|
| Raises : | Exception, when a required key is not set or is None. |
See also
Abstraction for an HTTP request.
Most extra methods and attributes are ported from webapp. Check the WebOb documentation for the ones not listed here.
A reference to the active WSGIApplication instance.
The matched route positional arguments.
The matched route keyword arguments.
A dictionary to register objects used during the request lifetime.
Constructs a Request object from a WSGI environment.
| Parameters: |
|
|---|
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: |
|
|---|---|
| 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. |
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: |
|
|---|---|
| Returns: | A (possibly empty) list of values. |
Returns a list of the arguments provided in the query and/or POST.
The return value is a list of strings.
Parses the given int argument, limiting it to the given range.
| Parameters: |
|
|---|---|
| Returns: | An int within the given range for the argument. |
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:
The status string, including code and message.
The response status message, as a string.
See also
Base HTTP request handler.
Implements most of webapp.RequestHandler interface.
A WSGIApplication instance.
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: |
|---|
Initializes this request handler with the given WSGI application, Request and Response.
| Parameters: |
|---|
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).
Clears the response and sets the given HTTP status code.
This doesn’t stop code execution; for this, use abort().
| Parameters: |
|
|---|
Raises an HTTPException.
This stops code execution, leaving the HTTP exception to be handled by an exception handler.
| Parameters: |
|
|---|
Issues an HTTP redirect to the given relative URI.
The arguments are described in redirect().
Convenience method mixing redirect() and uri_for().
The arguments are described in redirect() and uri_for().
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: |
|
|---|
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.
Performs a redirect.
Two keyword arguments can be passed through the URI route:
These are some other utilities also available for general use.
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.
Returns the active app instance.
| Returns: | A WSGIApplication instance. |
|---|
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: |
|
|---|---|
| Returns: | A Response instance. |
Convenience function mixing redirect() and uri_for().
Issues an HTTP redirect to a named URI built using uri_for().
| Parameters: |
|
|---|---|
| Returns: | A Response instance. |
The other arguments are described in redirect().
A standalone uri_for version that can be passed to templates.
See also
Raises an HTTPException.
| Parameters: |
|
|---|
Imports an object based on a string in dotted notation.
Simplified version of the function with same name from Werkzeug.
| Parameters: |
|
|---|---|
| Returns: | The imported object. |