Navigation

When it comes to combining multiple controller or view functions (however
you want to call them), you need a dispatcher. A simple way would be
applying regular expression tests on PATH_INFO and call registered
callback functions that return the value.

Werkzeug provides a much more powerful system, similar to Routes. All the
objects mentioned on this page must be imported from werkzeug.routing, not
from werkzeug!

So what does that do? First of all we create a new Map which stores
a bunch of URL rules. Then we pass it a list of Rule objects.

Each Rule object is instantiated with a string that represents a rule
and an endpoint which will be the alias for what view the rule represents.
Multiple rules can have the same endpoint, but should have different arguments
to allow URL construction.

The format for the URL rules is straightforward, but explained in detail below.

Inside the WSGI application we bind the url_map to the current request which will
return a new MapAdapter. This url_map adapter can then be used to match
or build domains for the current request.

Rule strings basically are just normal URL paths with placeholders in the
format <converter(arguments):name>, where converter and the arguments
are optional. If no converter is defined, the default converter is used
(which means string in the normal configuration).

URL rules that end with a slash are branch URLs, others are leaves. If you
have strict_slashes enabled (which is the default), all branch URLs that are
visited without a trailing slash will trigger a redirect to the same URL with
that slash appended.

The list of converters can be extended, the default converters are explained
below.

The map class stores all the URL rules and some configuration
parameters. Some of the configuration values are only stored on the
Map instance since those affect all rules, others are just defaults
and can be overridden for each rule. Note that you have to specify all
arguments besides the rules as keyword arguments!

Parameters:

rules – sequence of url rules for this map.

default_subdomain – The default subdomain for rules without a
subdomain defined.

charset – charset of the url. defaults to "utf-8"

strict_slashes – Take care of trailing slashes.

redirect_defaults – This will redirect to the default rule if it
wasn’t visited that way. This helps creating
unique URLs.

converters – A dict of converters that adds additional converters
to the list of converters. If you redefine one
converter this will override the original one.

sort_parameters – If set to True the url parameters are sorted.
See url_encode for more details.

sort_key – The sort key function for url_encode.

encoding_errors – the error method to use for decoding

host_matching – if set to True it enables the host matching
feature and disables the subdomain one. If
enabled the host parameter to rules is used
instead of the subdomain one.

The dictionary of converters. This can be modified after the class
was created, but will only affect rules added after the
modification. If the rules are defined with the list passed to the
class, the converters parameter to the constructor has to be used
instead.

Return a new MapAdapter with the details specified to the
call. Note that script_name will default to '/' if not further
specified or None. The server_name at least is a requirement
because the HTTP RFC requires absolute URLs for redirects and so all
redirect exceptions raised by Werkzeug will contain the full canonical
URL.

If no path_info is passed to match() it will use the default path
info passed to bind. While this doesn’t really make sense for
manual bind calls, it’s useful if you bind a map to a WSGI
environment which already contains the path info.

subdomain will default to the default_subdomain for this map if
no defined. If there is no default_subdomain you cannot use the
subdomain feature.

Like bind() but you can pass it an WSGI environment and it
will fetch the information from that dictionary. Note that because of
limitations in the protocol there is no way to get the current
subdomain and real server_name from the environment. If you don’t
provide it, Werkzeug will use SERVER_NAME and SERVER_PORT (or
HTTP_HOST if provided) as used server_name with disabled subdomain
feature.

If subdomain is None but an environment and a server name is
provided it will calculate the current subdomain automatically.
Example: server_name is 'example.com' and the SERVER_NAME
in the wsgi environ is 'staging.dev.example.com' the calculated
subdomain will be 'staging.dev'.

If the object passed as environ has an environ attribute, the value of
this attribute is used instead. This allows you to pass request
objects. Additionally PATH_INFO added as a default of the
MapAdapter so that you don’t have to pass the path info to
the match method.

Changed in version 0.5: previously this method accepted a bogus calculate_subdomain
parameter that did not have any effect. It was removed because
of that.

Changed in version 0.8: This will no longer raise a ValueError when an unexpected server
name was passed.

Iterate over all rules and check if the endpoint expects
the arguments provided. This is for example useful if you have
some URLs that expect a language code and others that do not and
you want to wrap the builder a bit so that the current language
code is automatically added if not provided but endpoints expect
it.

Parameters:

endpoint – the endpoint to check.

arguments – this function accepts one or more arguments
as positional arguments. Each one of them is
checked.

Building URLs works pretty much the other way round. Instead of
match you call build and pass it the endpoint and a dict of
arguments for the placeholders.

The build function also accepts an argument called force_external
which, if you set it to True will force external URLs. Per default
external URLs (include the server name) will only be used if the
target URL is on a different subdomain.

Does the complete dispatching process. view_func is called with
the endpoint and a dict with the values for the view. It should
look up the view function, call it, and return a response object
or WSGI application. http exceptions are not caught by default
so that applications can display nicer error messages by just
catching them by hand. If you want to stick with the default
error messages you can pass it catch_http_exceptions=True and
it will catch the http exceptions.

Here a small example for the dispatch usage:

fromwerkzeug.wrappersimportRequest,Responsefromwerkzeug.wsgiimportresponderfromwerkzeug.routingimportMap,Ruledefon_index(request):returnResponse('Hello from the index')url_map=Map([Rule('/',endpoint='index')])views={'index':on_index}@responderdefapplication(environ,start_response):request=Request(environ)urls=url_map.bind_to_environ(environ)returnurls.dispatch(lambdae,v:views[e](request,**v),catch_http_exceptions=True)

Keep in mind that this method might return exception objects, too, so
use Response.force_type to get a response object.

Parameters:

view_func – a function that is called with the endpoint as
first argument and the value dict as second. Has
to dispatch to the actual view function with this
information. (see above)

path_info – the path info to use for matching. Overrides the
path info specified on binding.

method – the HTTP method used for matching. Overrides the
method specified on binding.

catch_http_exceptions – set to True to catch any of the
werkzeug HTTPExceptions.

The usage is simple: you just pass the match method the current
path info as well as the method (which defaults to GET). The
following things can then happen:

you receive a NotFound exception that indicates that no URL is
matching. A NotFound exception is also a WSGI application you
can call to get a default page not found page (happens to be the
same object as werkzeug.exceptions.NotFound)

you receive a MethodNotAllowed exception that indicates that there
is a match for this URL but not for the current request method.
This is useful for RESTful applications.

you receive a RequestRedirect exception with a new_url
attribute. This exception is used to notify you about a request
Werkzeug requests from your WSGI application. This is for example the
case if you request /foo although the correct URL is /foo/
You can use the RequestRedirect instance as response-like object
similar to all other subclasses of HTTPException.

you get a tuple in the form (endpoint,arguments) if there is
a match (unless return_rule is True, in which case you get a tuple
in the form (rule,arguments))

If the path info is not passed to the match method the default path
info of the map is used (defaults to the root URL if not defined
explicitly).

All of the exceptions raised are subclasses of HTTPException so they
can be used as WSGI responses. They will all render generic error or
redirect pages.

A Rule represents one URL pattern. There are some options for Rule
that change the way it behaves and are passed to the Rule constructor.
Note that besides the rule-string all arguments must be keyword arguments
in order to not break the application on Werkzeug upgrades.

string

Rule strings basically are just normal URL paths with placeholders in
the format <converter(arguments):name> where the converter and the
arguments are optional. If no converter is defined the default
converter is used which means string in the normal configuration.

URL rules that end with a slash are branch URLs, others are leaves.
If you have strict_slashes enabled (which is the default), all
branch URLs that are matched without a trailing slash will trigger a
redirect to the same URL with the missing slash appended.

The converters are defined on the Map.

endpoint

The endpoint for this rule. This can be anything. A reference to a
function, a string, a number etc. The preferred way is using a string
because the endpoint is used for URL generation.

defaults

An optional dict with defaults for other rules with the same endpoint.
This is a bit tricky but useful if you want to have unique URLs:

A sequence of http methods this rule applies to. If not specified, all
methods are allowed. For example this can be useful if you want different
endpoints for POST and GET. If methods are defined and the path
matches but the method matched against is not in this list or in the
list of another rule for that path the error raised is of the type
MethodNotAllowed rather than NotFound. If GET is present in the
list of methods and HEAD is not, HEAD is added automatically.

Changed in version 0.6.1: HEAD is now automatically added to the methods if GET is
present. The reason for this is that existing code often did not
work properly in servers not rewriting HEAD to GET
automatically and it was not documented how HEAD should be
treated. This was considered a bug in Werkzeug because of that.

strict_slashes

Override the Map setting for strict_slashes only for this rule. If
not specified the Map setting is used.

build_only

Set this to True and the rule will never match but will create a URL
that can be build. This is useful if you have resources on a subdomain
or folder that are not handled by the WSGI application (like static data)

redirect_to

If given this must be either a string or callable. In case of a
callable it’s called with the url adapter that triggered the match and
the values of the URL as keyword arguments and has to return the target
for the redirect, otherwise it has to be a string with placeholders in
rule syntax:

deffoo_with_slug(adapter,id):# ask the database for the slug for the old id. this of# course has nothing to do with werkzeug.return'foo/'+Foo.get_slug_for_id(id)url_map=Map([Rule('/foo/<slug>',endpoint='foo'),Rule('/some/old/url/<slug>',redirect_to='foo/<slug>'),Rule('/other/old/url/<int:id>',redirect_to=foo_with_slug)])

When the rule is matched the routing system will raise a
RequestRedirect exception with the target for the redirect.

Keep in mind that the URL will be joined against the URL root of the
script so don’t use a leading slash on the target URL unless you
really mean root of that domain.

alias

If enabled this rule serves as an alias for another rule with the same
endpoint and arguments.

host

If provided and the URL map has host matching enabled this can be
used to provide a match rule for the whole host. This also means
that the subdomain feature is disabled.

As soon as you have more complex URL setups it’s a good idea to use rule
factories to avoid repetitive tasks. Some of them are builtin, others can
be added by subclassing RuleFactory and overriding get_rules.

You can easily add custom converters. The only thing you have to do is to
subclass BaseConverter and pass that new converter to the url_map.
A converter has to provide two public methods: to_python and to_url,
as well as a member that represents a regular expression. Here is a small
example:

Starting with Werkzeug 0.7 it’s also possible to do matching on the whole
host names instead of just the subdomain. To enable this feature you need
to pass host_matching=True to the Map constructor and provide
the host argument to all routes: