Routing¶
Routing is the process of matching and parsing a URL to something we can use.
Pulsar provides a flexible integrated
routing system you can use for that. It works by creating a
Router instance with its own rule and, optionally, additional
sub-routers for handling additional urls:
class Page(Router):
response_content_types = RouterParam(('text/html',
'text/plain',
'application/json'))
def get(self, request):
"This method handle requests with get-method"
...
def post(self, request):
"This method handle requests with post-method"
...
def delete(self, request):
"This method handle requests with delete-method"
...
...
middleware = Page('/bla')
Router¶
The middleware constructed in the snippet above
handles get and post methods at the /bla url.
The Router introduces a new element into pulsar WSGI handlers, the
wsgi request, a light-weight wrapper of the
WSGI environ.
For an exhaustive example on how to use the Router middleware make
sure you check out the HttpBin example.
-
class
pulsar.apps.wsgi.routers.Router(rule, *routes, **parameters)[source]¶ A WSGI middleware to handle client requests on multiple routes.
The user must implement the HTTP methods required by the application. For example if the route needs to serve a
GETrequest, theget(self, request)method must be implemented.Parameters: -
rule_methods¶ A class attribute built during class creation. It is an ordered dictionary mapping method names with a five-elements tuple containing information about a child route (See the
routedecorator).
-
response_content_types¶ A list/tuple of possible content types of a response to a client request.
The client request must accept at least one of the response content types, otherwise an HTTP
415exception occurs.
-
response_wrapper¶ Optional function which wraps all handlers of this
Router. The function must accept two parameters, the original handler and theWsgiRequest:def response_wrapper(handler, request): ... return handler(request)
-
full_route¶ The full
routefor thisRouter.It includes the
parentportion of the route if a parent router is available.
-
rule¶ The full
rulestring for thisRouter.It includes the
parentportion of the rule if aparentrouter is available.
-
path(**urlargs)[source]¶ The full path of this
Router.It includes the
parentportion of url if a parent router is available.
-
resolve(path, urlargs=None)[source]¶ Resolve a path and return a
(handler, urlargs)tuple orNoneif the path could not be resolved.
-
response(environ, args)[source]¶ Once the
resolve()method has matched the correctRouterfor serving the request, this matched router invokes this method to produce the WSGI response.
-
get_route(name)[source]¶ Get a child
Routerby itsname.This method search child routes recursively.
-
link(*args, **urlargs)[source]¶ Return an anchor
Htmlelement with the href attribute set to the url of thisRouter.
-
make_router(rule, method=None, handler=None, cls=None, name=None, **params)[source]¶ Create a new
Routerfrom aruleand parameters.This method is used during initialisation when building child Routers from the
rule_methods.
-
Media Router¶
The MediaRouter is a specialised Router for serving static
files such ass css, javascript, images and so forth.
-
class
pulsar.apps.wsgi.routers.MediaRouter(rule, path=None, show_indexes=False, default_suffix=None, default_file='index.html', serve_only=None, **params)[source]¶ A
Routerfor serving static media files from a given directory.Parameters: - rute – The top-level url for this router. For example
/mediawill serve the/media/<path:path>Route. - path – Check the
pathattribute. - show_indexes – Check the
show_indexesattribute.
-
path¶ The file-system path of the media files to serve.
-
show_indexes¶ If
True, the router will serve media file directories as well as media files.
-
serve_only¶ File suffixes to be served. When specified this is a set of suffixes (jpeg, png, json for example) which are served by this router if a file does not match the suffix it wont be served and the router return nothing so that other router can process the url.
-
default_file¶ The default file to serve when a directory is requested.
- rute – The top-level url for this router. For example
File Response¶
High level, battery included function for serving small and large files concurrently. Caveat, you app does not need to be asynchronous to use this method.
-
pulsar.apps.wsgi.routers.file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None)[source]¶ Utility for serving a local file
Typical usage:
from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): return wsgi.file_response(request, "<filepath>")
Parameters: - request – Wsgi request
- filepath – full path of file to serve
- block – Optional block size (default 1MB)
- status_code – Optional status code (default 200)
Returns: a
WsgiResponseobject
RouterParam¶
-
class
pulsar.apps.wsgi.routers.RouterParam(value=None)[source]¶ A
RouterParamis a way to flag aRouterparameter so that children can inherit the value if they don’t define their own.A
RouterParamis always defined as a class attribute and it is processed by theRoutermetaclass and stored in a dictionary available asparameterclass attribute.-
value¶ The value associated with this
RouterParam. This is the value stored in theRouter.parametersdictionary at key given by the class attribute specified in the class definition.
-
Route rules¶
Routing classes for matching and parsing urls.
Note
The route module was originally from the routing
module in werkzeug. Original License:
copyright (c) 2011 by the Werkzeug Team. License BSD
A Route is a class for relative url paths:
r1 = Route('bla')
r2 = Route('bla/foo')
Integers:
# accept any integer
Route('<int:size>')
# accept an integer between 1 and 200 only
Route('<int(min=1,max=200):size>')
Paths:
# accept any path (including slashes)
Route('<path:pages>')
Route('<path:pages>/edit')
Route decorator¶
-
class
pulsar.apps.wsgi.route.route(rule=None, method=None, defaults=None, position=None, re=False, **parameters)[source]¶ Decorator to create a child route from a
Routermethod.Typical usage:
from pulsar.apps.wsgi import Router, route class View(Router): def get(self, request): ... @route() def foo(self, request): ... @route('/bla', method='post') def handle2(self, request): ...
In this example,
Viewis the parent router which handle get requests only.The decorator injects the
rule_methodattribute to the method it decorates. The attribute is a five elements tuple which contains theRoute, the HTTPmethod, a dictionary of additionalparameters,positionand theorder. Position and order are internal integers used by theRouterwhen deciding the order of url matching. Ifpositionis not passed, the order will be given by the position of each method in theRouterclass.The decorated method are stored in the
Router.rule_methodsclass attribute.>>> len(View.rule_methods) 2 >>> View.rule_methods['foo'].rule /foo >>> View.rule_methods['foo'].method 'get' >>> View.rule_methods['handle2'].rule /bla >>> View.rule_methods['handle2'].method 'post'
Check the HttpBin example for a sample usage.
Parameters: - rule – Optional string for the relative url served by the method which is decorated. If not supplied, the method name is used.
- method – Optional HTTP method name. Default is get.
- defaults – Optional dictionary of default variable values used when
initialising the
Routeinstance. - position – Optional positioning of the router within the list of child routers of the parent router
- parameters – Additional parameters used when initialising
the
Routercreated by this decorator
Route¶
-
class
pulsar.apps.wsgi.route.Route(rule, defaults=None, is_re=False)[source]¶ A Route is a class with a relative
path.Parameters: - rule – a normal URL path with
placeholdersin the format<converter(parameters):name>where both theconverterand theparametersare optional. If noconverteris defined the default converter is used which meansstring,nameis the variable name. - defaults – optional dictionary of default values for the rule variables.
-
is_leaf¶ If
True, the route is equivalent to a file. For example/bla/foo
-
rule¶ The rule string, does not include the initial
'/'
-
path¶ The full rule for this route including initial
'/'.
-
variables¶ a set of variable names for this route. If the route has no variables, the set is empty.
- rule – a normal URL path with