将Flask中的URL还原为端点+参数 [英] Reverting a URL in Flask to the endpoint + arguments
问题描述
在Flask中解析URL以检索对端点的引用以及所有参数的字典的合适方法是什么?
What would be the appropriate way of resolving a URL within Flask to retrieve a reference to the endpoint as well as a dictionary of all the arguments?
举个例子,给定此路由,我想将'/user/nick'
解析为 profile
, {'username':'尼克'}
:
To provide an example, given this route, I'd like to resolve '/user/nick'
to profile
,{'username': 'nick'}
:
@app.route('/user/<username>')
def profile(username): pass
到目前为止,根据我的研究,Flask中的所有路线都存储在 app.url_map
下.该地图是 werkzeug.routing.Map 的实例,并且具有方法match()
原则上可以满足我的需求.但是,该方法是类的内部.
From my research so far, all routes in Flask are stored under app.url_map
. The map is an instance of werkzeug.routing.Map and it has a method match()
that would in principle do what I am looking for. However, that method is internal to the class.
推荐答案
为此,我研究了 url_for()
并将其反转的方法:
This is what I hacked for this purpose looking at url_for()
and reversing it:
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)
此方法的返回值是一个元组,第一个元素是端点名称,第二个是带有参数的字典.
The return value of this method is a tuple, with the first element being the endpoint name and the second a dictionary with the arguments.
我还没有对其进行广泛的测试,但是它在所有情况下都对我有用.
I haven't tested it extensively, but it worked for me in all cases.
这篇关于将Flask中的URL还原为端点+参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!