Get a flash drive view function that matches the url

I have several URLs and want to check if they specify a url rule in my Flask application. How can I check this using the checkbox?

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
+4
source share
1 answer

app.url_mapstores an object that maps and matches rules to endpoints. app.view_functionsdisplays endpoints for viewing features.

Call matchto match URL to endpoint and values. It will increase 404 if the route is not found, and 405 if the wrong method is specified. You will need the method as well as the corresponding 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.

+11

Source: https://habr.com/ru/post/1648555/


All Articles