See also
webapp2.
WSGIApplication
(routes=None, debug=False, config=None)[source]¶A WSGI-compliant application.
__call__
(environ, start_response)[source]¶Called by WSGI when a request comes in.
Parameters: |
|
---|---|
Returns: | An iterable with the response to return to the client. |
__init__
(routes=None, debug=False, config=None)[source]¶Initializes the WSGI application.
Parameters: |
|
---|
active_instance
= <LocalProxy unbound>¶Same as app
, for webapp compatibility. See set_globals()
.
allowed_methods
= frozenset(['HEAD', 'TRACE', 'GET', 'PUT', 'POST', 'OPTIONS', 'DELETE'])¶Allowed request methods.
app
= <LocalProxy unbound>¶Active WSGIApplication
instance. See set_globals()
.
clear_globals
()[source]¶Clears global variables. See set_globals()
.
debug
= False¶A general purpose flag to indicate development mode: if True, uncaught
exceptions are raised instead of using HTTPInternalServerError
.
error_handlers
= None¶A dictionary mapping HTTP error codes to callables to handle those
HTTP exceptions. See handle_exception()
.
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: |
|
---|---|
Returns: | A |
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: | |
---|---|
Returns: | The returned value from the error handler. |
registry
= None¶A dictionary to register objects used during the app lifetime.
request
= <LocalProxy unbound>¶Active Request
instance. See set_globals()
.
request_context_class
¶Class used for the request context object.
alias of RequestContext
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 . |
---|
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: |
|
---|
webapp2.
RequestContext
(app, environ)[source]¶Context for a single request.
The context is responsible for setting and cleaning global variables for a request.
__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.
__init__
(app, environ)[source]¶Initializes the request context.
Parameters: |
|
---|
See also
Router and URI routing
webapp2.
Router
(routes=None)[source]¶A URI router used to match, dispatch and build URIs.
__init__
(routes=None)[source]¶Initializes the router.
Parameters: | routes – A sequence of Route instances or, for simple routes,
tuples (regex, 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. |
add
(route)[source]¶Adds a route to this router.
Parameters: | route – A Route instance or, for simple routes, a tuple
(regex, handler) . |
---|
build
(request, name, args, kwargs)¶Returns a URI for a named Route
.
Parameters: |
|
---|---|
Returns: | An absolute or relative URI. |
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. |
default_builder
(request, name, args, kwargs)[source]¶Returns a URI for a named Route
.
Parameters: |
|
---|---|
Returns: | An absolute or relative URI. |
default_dispatcher
(request, response)[source]¶Dispatches a handler.
Parameters: | |
---|---|
Raises: |
|
Returns: | The returned value from the handler. |
default_matcher
(request)[source]¶Matches all routes against a request object.
The first one that matches is returned.
Parameters: | request – A Request instance. |
---|---|
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. |
dispatch
(request, response)¶Dispatches a handler.
Parameters: | |
---|---|
Raises: |
|
Returns: | The returned value from the handler. |
match
(request)¶Matches all routes against a request object.
The first one that matches is returned.
Parameters: | request – A Request instance. |
---|---|
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. |
route_class
¶Class used when the route is set as a tuple.
alias of SimpleRoute
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. |
---|
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_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. |
---|
webapp2.
BaseRoute
(template, handler=None, name=None, build_only=False)[source]¶Interface for URI routes.
build
(request, args, kwargs)[source]¶Returns a URI for this route.
Parameters: |
|
---|---|
Returns: | An absolute or relative URI. |
build_only
= False¶True if this route is only used for URI generation and never matches.
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. |
---|
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_routes
()[source]¶Generator to get all routes from a route.
Yields: | This route or all nested routes that it contains. |
---|
handler
= None¶The handler or string in dotted notation to be lazily imported.
handler_adapter
= None¶The handler, imported and ready for dispatching.
handler_method
= None¶The custom handler method, if handler is a class.
match
(request)[source]¶Matches all routes against a request object.
The first one that matches is returned.
Parameters: | request – A Request instance. |
---|---|
Returns: | A tuple (route, args, kwargs) if a route matched, or None. |
name
= None¶Route name, used to build URIs.
template
= None¶The regex template.
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: |
|
---|
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: |
|
---|
See also
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: |
|
---|---|
Raises: | Exception, when a required key is not set or is None. |
See also
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.
__init__
(environ, *args, **kwargs)[source]¶Constructs a Request object from a WSGI environment.
Parameters: | environ – A WSGI-compliant environment dictionary. |
---|
app
= None¶A reference to the active WSGIApplication
instance.
arguments
()[source]¶Returns a list of the arguments provided in the query and/or POST.
The return value is an ordered list of strings.
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: |
|
---|---|
Returns: | Return the value with the given name given in the request. If there are multiple values, this will only return the first one. Use get_all() to get multiple values. |
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: |
|
---|---|
Returns: | A (possibly empty) list of values. |
get_range
(name, min_value=None, max_value=None, default=0)[source]¶Parses the given int argument, limiting it to the given range.
Parameters: |
|
---|---|
Returns: | An int within the given range for the argument. |
registry
= None¶A dictionary to register objects used during the request lifetime.
route_args
= None¶The matched route positional arguments.
route_kwargs
= None¶The matched route keyword arguments.
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()
.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
.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. |
---|
status
¶The status string, including code and message.
status_message
¶The response status message, as a string.
See also
webapp2.
RequestHandler
(request=None, response=None)[source]¶Base HTTP request handler.
Implements most of webapp.RequestHandler
interface.
__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: |
---|
abort
(code, *args, **kwargs)[source]¶Raises an HTTPException
.
This stops code execution, leaving the HTTP exception to be handled by an exception handler.
Parameters: |
|
---|
app
= None¶A WSGIApplication
instance.
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). |
---|
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: |
|
---|
initialize
(request, response)[source]¶Initializes this request handler with the given WSGI application, Request and Response.
Parameters: |
---|
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()
.
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:
(handler, *args, **kwargs)
as arguments.These are some other utilities also available for general use.
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.
webapp2.
get_app
()[source]¶Returns the active app instance.
Returns: | A WSGIApplication 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: |
|
---|---|
Returns: | A |
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: |
|
---|---|
Returns: | A |
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
webapp2.
abort
(code, *args, **kwargs)[source]¶Raises an HTTPException
.
Parameters: |
|
---|
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: |
|
---|---|
Returns: | The imported object. |