在Flask中寻找url_for的反转

Dan*_*Dan 9 python rest json werkzeug flask

我正在使用FlaskFlask-RESTful来构建REST API.在此API中,我的一些资源包含与其他资源的URL关系.

当对这些资源执行POST请求时,我发现我需要与Flask的url_for()函数相反来解析传入的url.

例如,POST https://www.example.com/buildings可能包含以下json:

{
  "address": "123 Lyall St",
  ...
  "owner": {
      "href": "https://www.example.com/users/21414512"
  },
  "tenant": {
      "href": "https://www.example.com/users/16324642"
  },
}
Run Code Online (Sandbox Code Playgroud)

我想解析id ownertenant使用以下路由:

"https://www.example.com/users/<int:id>"
Run Code Online (Sandbox Code Playgroud)

在Flask或Werkzueg中有没有一种方便的方法可以做到这一点,还是我应该自己解析网址?能够重新使用已经定义的路线会很好...

我找到了这篇文章,但它似乎没有描述如何在请求之外执行此操作.

tbi*_*icr 10

最简单的方法创建测试请求上下文(感谢Leon Young):

with app.test_request_context(YOUR_URL) as request_ctx:
    url_rule = request_ctx.request.url_rule
Run Code Online (Sandbox Code Playgroud)

但是创建请求上下文的所有意义:

from flask.testing import make_test_environ_builder

builder = make_test_environ_builder(app, YOUR_URL)
environ = builder.get_environ()
url_adapter = app.url_map.bind_to_environ(environ)
url_rule, view_args = url_adapter.match(return_rule=True)
Run Code Online (Sandbox Code Playgroud)

如果没有理由检查协议和主机,您可以创建特殊匹配方法:

from functools import partial

url_adapter = app.url_map.bind('localhost')
match = partial(url_adapter.match, return_rule=True)
Run Code Online (Sandbox Code Playgroud)

并且无需协议和主机即可使用它:

owner_url_rule, owner_view_args = match('/users/21414512')
tenant_url_rule, tenant_view_args = match('/users/16324642')
Run Code Online (Sandbox Code Playgroud)


Mig*_*uel 5

我使用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)
Run Code Online (Sandbox Code Playgroud)

我通过查看它的实现url_for并逆向它来写这篇文章。

参数url可以是完整的 URL 或只是路径信息部分。返回值是一个包含端点名称和dict参数的元组。

免责声明:我还没有对其进行广泛的测试。我计划最终将其作为拉取请求提交,但似乎从未抽出时间来全面测试它并编写一些单元测试。如果它对您不起作用,请告诉我!