class documentation

class Rule(RuleFactory):

View In Hierarchy

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:

url_map = Map([
    Rule('/all/', defaults={'page': 1}, endpoint='all_entries'),
    Rule('/all/page/<int:page>', endpoint='all_entries')
])

If a user now visits http://example.com/all/page/1 he will be redirected to http://example.com/all/. If redirect_defaults is disabled on the Map instance this will only affect the URL generation.

subdomain

The subdomain rule string for this rule. If not specified the rule only matches for the default_subdomain of the map. If the map is not bound to a subdomain this feature is disabled.

Can be useful if you want to have user profiles on different subdomains and all subdomains are forwarded to your application:

url_map = Map([
    Rule('/', subdomain='<username>', endpoint='user/homepage'),
    Rule('/stats', subdomain='<username>', endpoint='user/stats')
])
methods
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.
strict_slashes
Override the Map setting for strict_slashes only for this rule. If not specified the Map setting is used.
merge_slashes
Override Map.merge_slashes for this rule.
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:

def foo_with_slug(adapter, id):
    # ask the database for the slug for the old id.  this of
    # course has nothing to do with werkzeug.
    return f'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.
websocket
If True, this rule is only matches for WebSocket (ws://, wss://) requests. By default, rules will only match for HTTP requests.
New in version 1.0: Added websocket.
New in version 1.0: Added merge_slashes.
New in version 0.7: Added alias and host.
Changed in version 0.6.1: HEAD is added to methods if GET is present.
Method __eq__ Undocumented
Method __init__ Undocumented
Method __repr__ Undocumented
Method __str__ Undocumented
Method bind Bind the url to a map and create a regular expression based on the information from the rule itself and the defaults from the map.
Method build Assembles the relative url for that rule and the subdomain. If building doesn't work for some reasons None is returned.
Method build​_compare​_key The build compare key for sorting.
Method compile Compiles the regular expression and stores it.
Method empty Return an unbound copy of this rule.
Method get​_converter Looks up the converter for the given parameter.
Method get​_empty​_kwargs Provides kwargs for instantiating empty copy with empty()
Method get​_rules Subclasses of RuleFactory have to override this method and return an iterable of rules.
Method match No summary
Method match​_compare​_key The match compare key for sorting.
Method provides​_defaults​_for Check if this rule has defaults for a given rule.
Method refresh Rebinds and refreshes the URL. Call this if you modified the rule in place.
Method suitable​_for Check if the dict of values has enough data for url generation.
Class Variable __hash__ Undocumented
Instance Variable alias Undocumented
Instance Variable arguments Undocumented
Instance Variable build​_only Undocumented
Instance Variable defaults Undocumented
Instance Variable endpoint Undocumented
Instance Variable host Undocumented
Instance Variable is​_leaf Undocumented
Instance Variable map Undocumented
Instance Variable merge​_slashes Undocumented
Instance Variable methods Undocumented
Instance Variable redirect​_to Undocumented
Instance Variable rule Undocumented
Instance Variable strict​_slashes Undocumented
Instance Variable subdomain Undocumented
Instance Variable websocket Undocumented
Static Method ​_get​_func​_code Undocumented
Method ​_compile​_builder Undocumented
Method ​_encode​_query​_vars Undocumented
Instance Variable ​_argument​_weights Undocumented
Instance Variable ​_build Undocumented
Instance Variable ​_build​_unknown Undocumented
Instance Variable ​_converters Undocumented
Instance Variable ​_regex Undocumented
Instance Variable ​_static​_weights Undocumented
Instance Variable ​_trace Undocumented
def __eq__(self, other):

Undocumented

Parameters
other:objectUndocumented
Returns
boolUndocumented
def __init__(self, string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, merge_slashes=None, redirect_to=None, alias=False, host=None, websocket=False):

Undocumented

Parameters
string:strUndocumented
defaults:t.Optional[t.Mapping[str, t.Any]]Undocumented
subdomain:t.Optional[str]Undocumented
methods:t.Optional[t.Iterable[str]]Undocumented
build​_only:boolUndocumented
endpoint:t.Optional[str]Undocumented
strict​_slashes:t.Optional[bool]Undocumented
merge​_slashes:t.Optional[bool]Undocumented
redirect​_to:t.Optional[t.Union[str, t.Callable[..., str]]]Undocumented
alias:boolUndocumented
host:t.Optional[str]Undocumented
websocket:boolUndocumented
def __repr__(self):

Undocumented

Returns
strUndocumented
def __str__(self):

Undocumented

Returns
strUndocumented
def bind(self, map, rebind=False):
Bind the url to a map and create a regular expression based on the information from the rule itself and the defaults from the map.
Parameters
map:MapUndocumented
rebind:boolUndocumented
Unknown Field: internal
def build(self, values, append_unknown=True):
Assembles the relative url for that rule and the subdomain. If building doesn't work for some reasons None is returned.
Parameters
values:t.Mapping[str, t.Any]Undocumented
append​_unknown:boolUndocumented
Returns
t.Optional[t.Tuple[str, str]]Undocumented
Unknown Field: internal
def build_compare_key(self):
The build compare key for sorting.
Returns
t.Tuple[int, int, int]Undocumented
Unknown Field: internal
def compile(self):
Compiles the regular expression and stores it.
def empty(self):

Return an unbound copy of this rule.

This can be useful if want to reuse an already bound URL for another map. See get_empty_kwargs to override what keyword arguments are provided to the new copy.

Returns
RuleUndocumented
def get_converter(self, variable_name, converter_name, args, kwargs):

Looks up the converter for the given parameter.

New in version 0.9.
Parameters
variable​_name:strUndocumented
converter​_name:strUndocumented
args:t.TupleUndocumented
kwargs:t.Mapping[str, t.Any]Undocumented
Returns
BaseConverterUndocumented
def get_empty_kwargs(self):

Provides kwargs for instantiating empty copy with empty()

Use this method to provide custom keyword arguments to the subclass of Rule when calling some_rule.empty(). Helpful when the subclass has custom keyword arguments that are needed at instantiation.

Must return a dict that will be provided as kwargs to the new instance of Rule, following the initial self.rule value which is always provided as the first, required positional argument.

Returns
t.Mapping[str, t.Any]Undocumented
def get_rules(self, map):
Subclasses of RuleFactory have to override this method and return an iterable of rules.
Parameters
map:MapUndocumented
Returns
t.Iterator[Rule]Undocumented
def match(self, path, method=None):

Check if the rule matches a given path. Path is a string in the form "subdomain|/path" and is assembled by the map. If the map is doing host matching the subdomain part will be the host instead.

If the rule matches a dict with the converted values is returned, otherwise the return value is None.

Parameters
path:strUndocumented
method:t.Optional[str]Undocumented
Returns
t.Optional[t.MutableMapping[str, t.Any]]Undocumented
Unknown Field: internal
def match_compare_key(self):

The match compare key for sorting.

Current implementation:

  1. rules without any arguments come first for performance reasons only as we expect them to match faster and some common ones usually don't have any arguments (index pages etc.)
  2. rules with more static parts come first so the second argument is the negative length of the number of the static weights.
  3. we order by static weights, which is a combination of index and length
  4. The more complex rules come first so the next argument is the negative length of the number of argument weights.
  5. lastly we order by the actual argument weights.
Returns
t.Tuple[bool, int, t.Iterable[t.Tuple[int, int]], int, t.Iterable[int]]Undocumented
Unknown Field: internal
def provides_defaults_for(self, rule):
Check if this rule has defaults for a given rule.
Parameters
rule:RuleUndocumented
Returns
boolUndocumented
Unknown Field: internal
def refresh(self):
Rebinds and refreshes the URL. Call this if you modified the rule in place.
Unknown Field: internal
def suitable_for(self, values, method=None):
Check if the dict of values has enough data for url generation.
Parameters
values:t.Mapping[str, t.Any]Undocumented
method:t.Optional[str]Undocumented
Returns
boolUndocumented
Unknown Field: internal
__hash__ =

Undocumented

alias =

Undocumented

arguments =

Undocumented

build_only =

Undocumented

defaults =

Undocumented

endpoint: str =

Undocumented

host =

Undocumented

is_leaf =

Undocumented

map =

Undocumented

merge_slashes =

Undocumented

methods =

Undocumented

redirect_to =

Undocumented

rule =

Undocumented

strict_slashes =

Undocumented

subdomain =

Undocumented

websocket =

Undocumented

@staticmethod
def _get_func_code(code, name):

Undocumented

Parameters
code:CodeTypeUndocumented
name:strUndocumented
Returns
t.Callable[..., t.Tuple[str, str]]Undocumented
def _compile_builder(self, append_unknown=True):

Undocumented

Parameters
append​_unknown:boolUndocumented
Returns
t.Callable[..., t.Tuple[str, str]]Undocumented
def _encode_query_vars(self, query_vars):

Undocumented

Parameters
query​_vars:t.Mapping[str, t.Any]Undocumented
Returns
strUndocumented
_argument_weights: t.List[int] =

Undocumented

_build =

Undocumented

_build_unknown =

Undocumented

_converters: t.Dict[str, BaseConverter] =

Undocumented

_regex =

Undocumented

_static_weights: t.List[t.Tuple[int, int]] =

Undocumented

_trace: list =

Undocumented