python - 获取匹配某个url的Flask View 函数

标签 python flask werkzeug

我有一些 url 路径,想检查它们是否指向我的 Flask 应用程序中的 url 规则。我如何使用 Flask 检查这个?

from flask import Flask, json, request, Response

app = Flask('simple_app')

@app.route('/foo/<bar_id>', methods=['GET'])
def foo_bar_id(bar_id):
    if request.method == 'GET':
        return Response(json.dumps({'foo': bar_id}), status=200)

@app.route('/bar', methods=['GET'])
def bar():
    if request.method == 'GET':
        return Response(json.dumps(['bar']), status=200)
test_route_a = '/foo/1'  # return foo_bar_id function
test_route_b = '/bar'  # return bar function

最佳答案

app.url_map存储映射和匹配规则与端点的对象。 app.view_functions将端点映射到 View 函数。

调用match将 url 与端点和值相匹配。如果找不到路由,它将引发 404,如果指定了错误的方法,则会引发 405。您需要匹配方法和 url。

重定向被视为异常,您需要以递归方式捕获和测试它们以找到 View 函数。

可以添加不映射到 View 的规则,您需要在查找 View 时捕获 KeyError

from werkzeug.routing import RequestRedirect, MethodNotAllowed, NotFound

def get_view_function(url, method='GET'):
    """Match a url and return the view and arguments
    it will be called with, or None if there is no view.
    """

    adapter = app.url_map.bind('localhost')

    try:
        match = adapter.match(url, method=method)
    except RequestRedirect as e:
        # recursively match redirects
        return get_view_function(e.new_url, method)
    except (MethodNotAllowed, NotFound):
        # no match
        return None

    try:
        # return the view function and arguments
        return app.view_functions[match[0]], match[1]
    except KeyError:
        # no view is associated with the endpoint
        return None

还有更多选项可以传递给 bind要影响如何进行匹配,请参阅文档了解详细信息。

View 函数也可以引发 404(或其他)错误,因此这只能保证 url 将匹配 View ,而不是 View 返回 200 响应。

关于python - 获取匹配某个url的Flask View 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38488134/

相关文章:

python - 如何随时间创建重复的数据框并将其映射到时间列表?

javascript - 无法将 jinja2 变量传递到 javascript 代码段中

python - 通过nosetests测试flask应用程序时获取IP地址

python - Windows Azure API : Programmatically create VM

python - 一帧上显示不同的帧

python - Flask 服务器启动问题 - 地址已在使用中

python - 将 Flask 开发服务器配置为在整个网络中可见

python - flask 蓝图索引URL不断添加斜杠

python - 检查字符串是否包含希伯来字符的正确方法

Python flask 暴露给外部可见