Last active
December 14, 2015 18:39
-
-
Save Xion/5130642 to your computer and use it in GitHub Desktop.
Enhance Flask url_for() with optional _strict argument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from flask import url_for | |
from myflaskapp import app | |
def url_for_ex(endpoint, **values): | |
"""Improved version of standard Flask's :func:`url_for` | |
that accepts an additional, optional ``_strict`` argument. | |
:param _strict: If ``False``, values for the endpoint are not checked | |
for compatibility with types defined in the URL rule. | |
Default: ``True``. | |
""" | |
strict = values.pop('_strict', True) | |
if not strict: | |
# search for matching URL rule; if that fails, we will just | |
# invoke url_for() normally so that Flask can handle the error | |
url_arguments = set(key for key in values.iterkeys() | |
if not key.startswith('_')) | |
url_rule = None | |
for rule in app.url_map.iter_rules(endpoint): | |
rule_arguments = set(rule._converters.iterkeys()) | |
if rule_arguments == url_arguments: | |
url_rule = rule.rule | |
break | |
if url_rule: | |
# replace argument placeholders in the URL rule (``<int:foo>``...) | |
# with values provided for those arguments | |
regex = '|'.join(r'\<(?:\w+\:)?(%s)\>' % arg for arg in values) | |
return re.sub(regex, lambda m: str(values[m.group(1)]), url_rule) | |
return url_for(endpoint, **values) | |
app.jinja_env.globals['url_for'] = url_for_ex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment