【问题标题】:Get the Flask view function that matches a url获取与 url 匹配的 Flask 视图函数
【发布时间】:2016-11-24 02:18:11
【问题描述】:

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

【问题讨论】:

    标签: python flask werkzeug


    【解决方案1】:

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

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

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

    可以添加不映射到视图的规则,您需要在查找视图时捕获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 来影响如何进行匹配,请参阅文档了解详细信息。

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

    【讨论】:

      【解决方案2】:

      除了@davidism 的答案(flask 的核心开发者)。 注意如果要发现flask app处理的当前url的查看功能。你可以使用flask的Request对象:

      Flask 中默认使用的请求对象。记得 匹配的端点和视图参数。

      还有Flask.view_functtions

      #:将端点名称映射到视图函数的字典。 #: 注册一个视图函数,使用:meth:route装饰器。

       def get_view_function():
           if request.url_rule:
              return current_app.view_functions.get(request.url_rule.endpoint, None)
      

      【讨论】:

        猜你喜欢
        • 2012-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-22
        • 2020-12-13
        • 2012-09-11
        相关资源
        最近更新 更多