Created
January 7, 2016 08:26
-
-
Save allanlei/9497a44a38cd3d1d4462 to your computer and use it in GitHub Desktop.
Reverse url_for for Flask
This file contains 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
# REF: http://stackoverflow.com/a/19637175/1198679 | |
from flask.globals import _app_ctx_stack, _request_ctx_stack | |
from werkzeug.urls import url_parse | |
def route_from(url, method = None): | |
appctx = _app_ctx_stack.top | |
reqctx = _request_ctx_stack.top | |
if appctx is None: | |
raise RuntimeError('Attempted to match a URL without the ' | |
'application context being pushed. This has to be ' | |
'executed when application context is available.') | |
if reqctx is not None: | |
url_adapter = reqctx.url_adapter | |
else: | |
url_adapter = appctx.url_adapter | |
if url_adapter is None: | |
raise RuntimeError('Application was not able to create a URL ' | |
'adapter for request independent URL matching. ' | |
'You might be able to fix this by setting ' | |
'the SERVER_NAME config variable.') | |
parsed_url = url_parse(url) | |
if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name: | |
raise NotFound() | |
return url_adapter.match(parsed_url.path, method) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment