2016-07-20 3 views
4

URL 경로가 있고 Flask 앱에서 URL 규칙을 가리키는 지 확인하고 싶습니다. 플라스크를 사용하여 이것을 어떻게 확인할 수 있습니까?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 
+0

[url_for] (http://flask.pocoo.org/docs/0.11/quickstart/#url-building)에 관심이있을 수 있습니다. – squiguy

+0

@squiguy,'url_for'는'endpoint'와 선택적인'values'로부터 url을 생성합니다. URL을 가져다가 관련 엔드 포인트를 찾으면됩니다. 어떤 의미에서는'url_for'의 반대가 필요합니다. –

답변

11

app.url_map 매장지도와 엔드 포인트와 규칙에 일치하는 객체입니다. app.view_functions은 엔드 포인트를보기 기능에 맵핑합니다.

URL을 끝점과 값과 일치 시키려면 match으로 전화하십시오. 경로를 찾지 못하면 404가 나오고 잘못된 방법이 지정되면 405가 발생합니다. 일치시킬 URL과 메소드가 필요합니다.

리디렉션은 예외로 처리되므로보기 기능을 찾으려면 리디렉션을 재귀 적으로 catch하고 테스트해야합니다.

보기에 매핑되지 않는 규칙을 추가 할 수 있습니다.보기를 찾을 때 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 오류 (또는 기타 오류)가 발생할 수 있으므로보기가 200 응답을 반환하는 것이 아니라 URL이보기와 일치합니다.