获取与网址匹配的Flask视图功能

Phi*_*tin 10 python werkzeug flask

我有一些网址路径,想检查他们是否指向我的Flask应用中的网址规则.如何使用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)
Run Code Online (Sandbox Code Playgroud)
test_route_a = '/foo/1'  # return foo_bar_id function
test_route_b = '/bar'  # return bar function
Run Code Online (Sandbox Code Playgroud)

dav*_*ism 19

app.url_map存储映射并将规则与端点匹配的对象. app.view_functions映射端点以查看功能.

调用match以匹配端点和值的URL.如果找不到路由,它将引发404;如果指定了错误的方法,则引发405.您需要该方法以及匹配的网址.

重定向被视为异常,您需要以递归方式捕获并测试这些异常以查找视图函数.

可以添加不映射到视图的规则,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
Run Code Online (Sandbox Code Playgroud)

可以传递更多选项bind以影响匹配方式,有关详细信息,请参阅文档.

视图函数也可能引发404(或其他)错误,因此这只能保证网址与视图匹配,而不是视图返回200响应.