URL Routing¶
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!
Quickstart¶
Here is a simple example which could be the URL definition for a blog:
from werkzeug.routing import Map, Rule, NotFound, RequestRedirect
url_map = Map([
Rule('/', endpoint='blog/index'),
Rule('/<int:year>/', endpoint='blog/archive'),
Rule('/<int:year>/<int:month>/', endpoint='blog/archive'),
Rule('/<int:year>/<int:month>/<int:day>/', endpoint='blog/archive'),
Rule('/<int:year>/<int:month>/<int:day>/<slug>',
endpoint='blog/show_post'),
Rule('/about', endpoint='blog/about_me'),
Rule('/feeds/', endpoint='blog/feeds'),
Rule('/feeds/<feed_name>.rss', endpoint='blog/show_feed')
])
def application(environ, start_response):
urls = url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
except HTTPException, e:
return e(environ, start_response)
start_response('200 OK', [('Content-Type', 'text/plain')])
return [f'Rule points to {endpoint!r} with arguments {args!r}']
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.
The MapAdapter.match() method can then either return a tuple in the form
(endpoint, args) or raise one of the three exceptions
NotFound, MethodNotAllowed,
or RequestRedirect. For more details about those
exceptions have a look at the documentation of the MapAdapter.match() method.
Rule Format¶
Rule strings are URL paths with placeholders for variable parts in the
format <converter(arguments):name>. converter and arguments
(with parentheses) are optional. If no converter is given, the
default converter is used (string by default). The available
converters are discussed below.
Rules that end with a slash are “branches”, others are “leaves”. If
strict_slashes is enabled (the default), visiting a branch URL
without a trailing slash will redirect to the URL with a slash appended.
Many HTTP servers merge consecutive slashes into one when receiving
requests. If merge_slashes is enabled (the default), rules will
merge slashes in non-variable parts when matching and building. Visiting
a URL with consecutive slashes will redirect to the URL with slashes
merged. If you want to disable merge_slashes for a Rule or
Map, you’ll also need to configure your web server
appropriately.
Built-in Converters¶
Converters for common types of URL variables are built-in. The available
converters can be overridden or extended through Map.converters.
-
class
werkzeug.routing.UnicodeConverter(map, minlength=1, maxlength=None, length=None)¶ This converter is the default converter and accepts any string but only one path segment. Thus the string can not include a slash.
This is the default validator.
Example:
Rule('/pages/<page>'), Rule('/<string(length=2):lang_code>')
-
class
werkzeug.routing.PathConverter(map, *args, **kwargs)¶ Like the default
UnicodeConverter, but it also matches slashes. This is useful for wikis and similar applications:Rule('/<path:wikipage>') Rule('/<path:wikipage>/edit')
-
class
werkzeug.routing.AnyConverter(map, *items)¶ Matches one of the items provided. Items can either be Python identifiers or strings:
Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>')
-
class
werkzeug.routing.IntegerConverter(map, fixed_digits=0, min=None, max=None, signed=False)¶ This converter only accepts integer values:
Rule("/page/<int:page>")
By default it only accepts unsigned, positive values. The
signedparameter will enable signed, negative values.Rule("/page/<int(signed=True):page>")
- Parameters
fixed_digits (int) – The number of fixed digits in the URL. If you set this to
4for example, the rule will only match if the URL looks like/0001/. The default is variable length.min (Optional[int]) – The minimal value.
max (Optional[int]) – The maximal value.
signed (bool) – Allow signed (negative) values.
- Return type
Changelog
New in version 0.15: The
signedparameter.
-
class
werkzeug.routing.FloatConverter(map, min=None, max=None, signed=False)¶ This converter only accepts floating point values:
Rule("/probability/<float:probability>")
By default it only accepts unsigned, positive values. The
signedparameter will enable signed, negative values.Rule("/offset/<float(signed=True):offset>")
- Parameters
- Return type
Changelog
New in version 0.15: The
signedparameter.