我有一些 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/