在Flask中寻找url_for的逆函数 [英] Looking for inverse of url_for in Flask
问题描述
我正在使用烧瓶和
I am using Flask and Flask-RESTful to build a REST API. Within this API some of my resources contain url relations to other resources.
对这些资源执行POST请求时,我发现我需要Flask的url_for()函数的逆函数来解析传入的URL.
When performing POST requests to these resources I am finding that I am needing the inverse of Flask's url_for() function to parse the incoming url.
例如,到https://www.example.com/buildings
的POST可能包含以下json:
For example, a POST to https://www.example.com/buildings
may contain the following json:
{
"address": "123 Lyall St",
...
"owner": {
"href": "https://www.example.com/users/21414512"
},
"tenant": {
"href": "https://www.example.com/users/16324642"
},
}
我想使用以下路由来解析owner
和tenant
中的ID:
I would like to parse the id out of owner
and tenant
using the following route:
"https://www.example.com/users/<int:id>"
在Flask或Werkzueg中是否有简便的方法可以做到这一点,还是我应该自己解析网址?能够重新使用已经定义的路由会很好...
Is there a convenient way to do this within Flask or Werkzueg or should I just parse the url myself? It would be nice to be able to re-use the already defined route...
我发现此发布,但似乎并未描述如何在请求之外进行操作.
I found this post but it does not seem to describe how to do it outside of a request.
推荐答案
我在下面使用route_from
函数:
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)
我通过查看url_for
的实现并将其反转来编写此代码.
I wrote this by looking at the implementation of url_for
and reversing it.
url
参数可以是完整的URL,也可以只是路径信息部分.返回值是带有端点名称的元组和带有参数的dict
.
The url
argument can be a complete URL or just the path info portion. The return value is a tuple with the endpoint name and a dict
with the arguments.
免责声明:我尚未对其进行广泛的测试.我原本打算最终将它作为请求请求提交,但似乎从来没有经过全面测试并编写了一些单元测试.如果它对您不起作用,请告诉我!
Disclaimer: I haven't tested it extensively. I was planning to eventually submit it as a pull request, but never seem to get around to fully test it and write some unit tests. If it does not work for you, let me know!
这篇关于在Flask中寻找url_for的逆函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!