获取与网址匹配的Flask视图函数 [英] Get the Flask view function that matches a url

查看:54
本文介绍了获取与网址匹配的Flask视图函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some url paths and want to check if they point to a url rule in my Flask app. How can I check this using 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 映射端点查看功能.

app.url_map stores the object that maps and matches rules with endpoints. app.view_functions maps endpoints to view functions.

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

Call match to match a url to an endpoint and values. It will raise 404 if the route is not found, and 405 if the wrong method is specified. You'll need the method as well as the url to match.

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

Redirects are treated as exceptions, you'll need to catch and test these recursively to find the view function.

可以添加未映射到视图的规则,查找视图时需要捕获 KeyError .

It's possible to add rules that don't map to views, you'll need to catch KeyError when looking up the view.

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 影响匹配的方式,请参阅文档以了解详细信息.

There are many more options that can be passed to bind to effect how matches are made, see the docs for details.

view函数还会引发404(或其他)错误,因此这仅保证url将匹配视图,而不保证该视图返回200响应.

The view function can also raise 404 (or other) errors, so this only guarantees that a url will match a view, not that the view returns a 200 response.

这篇关于获取与网址匹配的Flask视图函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆