class documentation

class MapAdapter:

View In Hierarchy

Returned by Map.bind or Map.bind_to_environ and does the URL matching and building based on runtime information.
Method __init__ Undocumented
Method allowed​_methods Returns the valid methods that match for a given path.
Method build 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.
Method dispatch No summary
Method encode​_query​_args Undocumented
Method get​_default​_redirect A helper that returns the URL to redirect to if it finds one. This is used for default redirecting only.
Method get​_host Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name.
Method make​_alias​_redirect​_url Internally called to make an alias redirect URL.
Method make​_redirect​_url Creates a redirect URL.
Method match 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:
Method test Test if a rule would match. Works like match but returns True if the URL matches, or False if it does not exist.
Instance Variable default​_method Undocumented
Instance Variable map Undocumented
Instance Variable path​_info Undocumented
Instance Variable query​_args Undocumented
Instance Variable script​_name Undocumented
Instance Variable server​_name Undocumented
Instance Variable subdomain Undocumented
Instance Variable url​_scheme Undocumented
Instance Variable websocket Undocumented
Method ​_partial​_build Helper for build. Returns subdomain and path for the rule that accepts this endpoint, values and method.
def __init__(self, map, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args=None):

Undocumented

Parameters
map:MapUndocumented
server​_name:strUndocumented
script​_name:strUndocumented
subdomain:t.Optional[str]Undocumented
url​_scheme:strUndocumented
path​_info:strUndocumented
default​_method:strUndocumented
query​_args:t.Optional[t.Union[t.Mapping[str, t.Any], str]]Undocumented
def allowed_methods(self, path_info=None):

Returns the valid methods that match for a given path.

New in version 0.7.
Parameters
path​_info:t.Optional[str]Undocumented
Returns
t.Iterable[str]Undocumented
def build(self, endpoint, values=None, method=None, force_external=False, append_unknown=True, url_scheme=None):

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.

>>> m = Map([
...     Rule('/', endpoint='index'),
...     Rule('/downloads/', endpoint='downloads/index'),
...     Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.build("index", {})
'/'
>>> urls.build("downloads/show", {'id': 42})
'/downloads/42'
>>> urls.build("downloads/show", {'id': 42}, force_external=True)
'http://example.com/downloads/42'

Because URLs cannot contain non ASCII data you will always get bytes back. Non ASCII characters are urlencoded with the charset defined on the map instance.

Additional values are converted to strings and appended to the URL as URL querystring parameters:

>>> urls.build("index", {'q': 'My Searchstring'})
'/?q=My+Searchstring'

When processing those additional values, lists are furthermore interpreted as multiple values (as per werkzeug.datastructures.MultiDict):

>>> urls.build("index", {'q': ['a', 'b', 'c']})
'/?q=a&q=b&q=c'

Passing a MultiDict will also add multiple values:

>>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b'))))
'/?p=z&q=a&q=b'

If a rule does not exist when building a BuildError exception is raised.

The build method accepts an argument called method which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified.

Changed in version 2.0: Added the url_scheme parameter.
New in version 0.6: Added the append_unknown parameter.
Parameters
endpoint:strthe endpoint of the URL to build.
values:t.Optional[t.Mapping[str, t.Any]]the values for the URL to build. Unhandled values are appended to the URL as query parameters.
method:t.Optional[str]the HTTP method for the rule if there are different URLs for different methods on the same endpoint.
force​_external:boolenforce full canonical external URLs. If the URL scheme is not provided, this will generate a protocol-relative URL.
append​_unknown:boolunknown parameters are appended to the generated URL as query string argument. Disable this if you want the builder to ignore those.
url​_scheme:t.Optional[str]Scheme to use in place of the bound url_scheme.
Returns
strUndocumented
def dispatch(self, view_func, path_info=None, method=None, catch_http_exceptions=False):

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:

from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import responder
from werkzeug.routing import Map, Rule

def on_index(request):
    return Response('Hello from the index')

url_map = Map([Rule('/', endpoint='index')])
views = {'index': on_index}

@responder
def application(environ, start_response):
    request = Request(environ)
    urls = url_map.bind_to_environ(environ)
    return urls.dispatch(lambda e, 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:t.Callable[[str, t.Mapping[str, t.Any]], WSGIApplication]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:t.Optional[str]the path info to use for matching. Overrides the path info specified on binding.
method:t.Optional[str]the HTTP method used for matching. Overrides the method specified on binding.
catch​_http​_exceptions:boolset to True to catch any of the werkzeug HTTPExceptions.
Returns
WSGIApplicationUndocumented
def encode_query_args(self, query_args):

Undocumented

Parameters
query​_args:t.Union[t.Mapping[str, t.Any], str]Undocumented
Returns
strUndocumented
def get_default_redirect(self, rule, method, values, query_args):
A helper that returns the URL to redirect to if it finds one. This is used for default redirecting only.
Parameters
rule:RuleUndocumented
method:strUndocumented
values:t.MutableMapping[str, t.Any]Undocumented
query​_args:t.Union[t.Mapping[str, t.Any], str]Undocumented
Returns
t.Optional[str]Undocumented
Unknown Field: internal
def get_host(self, domain_part):
Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name.
Parameters
domain​_part:t.Optional[str]Undocumented
Returns
strUndocumented
def make_alias_redirect_url(self, path, endpoint, values, method, query_args):
Internally called to make an alias redirect URL.
Parameters
path:strUndocumented
endpoint:strUndocumented
values:t.Mapping[str, t.Any]Undocumented
method:strUndocumented
query​_args:t.Union[t.Mapping[str, t.Any], str]Undocumented
Returns
strUndocumented
def make_redirect_url(self, path_info, query_args=None, domain_part=None):
Creates a redirect URL.
Parameters
path​_info:strUndocumented
query​_args:t.Optional[t.Union[t.Mapping[str, t.Any], str]]Undocumented
domain​_part:t.Optional[str]Undocumented
Returns
strUndocumented
Unknown Field: internal
def match(self, path_info=None, method=None, return_rule=False, query_args=None, websocket=None):

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 receive a WebsocketMismatch exception if the only match is a WebSocket rule but the bind is an HTTP request, or if the match is an HTTP rule but the bind is a WebSocket request.
  • 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.

Here is a small example for matching:

>>> m = Map([
...     Rule('/', endpoint='index'),
...     Rule('/downloads/', endpoint='downloads/index'),
...     Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.match("/", "GET")
('index', {})
>>> urls.match("/downloads/42")
('downloads/show', {'id': 42})

And here is what happens on redirect and missing URLs:

>>> urls.match("/downloads")
Traceback (most recent call last):
  ...
RequestRedirect: http://example.com/downloads/
>>> urls.match("/missing")
Traceback (most recent call last):
  ...
NotFound: 404 Not Found
New in version 1.0: Added websocket.
Changed in version 0.8: query_args can be a string.
New in version 0.7: Added query_args.
New in version 0.6: Added return_rule.
Parameters
path​_info:t.Optional[str]the path info to use for matching. Overrides the path info specified on binding.
method:t.Optional[str]the HTTP method used for matching. Overrides the method specified on binding.
return​_rule:boolreturn the rule that matched instead of just the endpoint (defaults to False).
query​_args:t.Optional[t.Union[t.Mapping[str, t.Any], str]]optional query arguments that are used for automatic redirects as string or dictionary. It's currently not possible to use the query arguments for URL matching.
websocket:t.Optional[bool]Match WebSocket instead of HTTP requests. A websocket request has a ws or wss url_scheme. This overrides that detection.
Returns
t.Tuple[t.Union[str, Rule], t.Mapping[str, t.Any]]Undocumented
def test(self, path_info=None, method=None):
Test if a rule would match. Works like match but returns True if the URL matches, or False if it does not exist.
Parameters
path​_info:t.Optional[str]the path info to use for matching. Overrides the path info specified on binding.
method:t.Optional[str]the HTTP method used for matching. Overrides the method specified on binding.
Returns
boolUndocumented
default_method =

Undocumented

map =

Undocumented

path_info =

Undocumented

query_args =

Undocumented

script_name =

Undocumented

server_name =

Undocumented

subdomain =

Undocumented

url_scheme =

Undocumented

websocket =

Undocumented

def _partial_build(self, endpoint, values, method, append_unknown):
Helper for build. Returns subdomain and path for the rule that accepts this endpoint, values and method.
Parameters
endpoint:strUndocumented
values:t.Mapping[str, t.Any]Undocumented
method:t.Optional[str]Undocumented
append​_unknown:boolUndocumented
Returns
t.Optional[t.Tuple[str, str, bool]]Undocumented
Unknown Field: internal