한 가지 방법은 등록 된 규칙의 match_compare_key()
방법을 위장하여 정렬 알고리즘 규칙을 속임수입니다.이 해킹은 청사진이 아닌 app.route()
(Flask 개체)으로 직접 등록 된 경로에서만 작동합니다. Blueprints의 경로는 기본 앱의 청사진 등록시에만 글로벌 URL Map에 추가되므로 생성 된 규칙을 수정하기가 어렵습니다.
# an ordinary route
@app.route('/<var1>/<var2>/<var3>')
def some_view(var1, var2, var3):
pass
# let's find the rule that was just generated
rule = app.url_map._rules[-1]
# we create some comparison keys:
# increase probability that the rule will be near or at the top
top_compare_key = False, -100, [(-2, 0)]
# increase probability that the rule will be near or at the bottom
bottom_compare_key = True, 100, [(2, 0)]
# rig rule.match_compare_key() to return the spoofed compare_key
rule.match_compare_key = lambda: top_compare_key
이 경우 생성 된 스푸핑 된 함수는 규칙 객체에 바인딩되지 않습니다. 따라서 rule.match_compare_key()
을 호출하면 함수에 self
인수가 수신되지 않습니다. 제대로 기능을 결합 할 경우, 대신에이 작업을 수행 :
spoof = lambda self: top_compare_key
rule.match_compare_key = spoof.__get__(rule, type(rule))
우리는 장식
def weighted_route(*args, **kwargs):
def decorator(view_func):
compare_key = kwargs.pop('compare_key', None)
# register view_func with route
app.route(*args, **kwargs)(view_func)
if compare_key is not None:
rule = app.url_map._rules[-1]
rule.match_compare_key = lambda: compare_key
return view_func
return decorator
# can be used like @app.route(). To weight the rule, just provide
# the `compare_key` param.
@weighted_route('/<var1>/<var2>/<var3>', compare_key=bottom_compare_key)
def some_view(var1, var2, var3):
pass
컨텍스트 매니저로 구현 된 같은 해킹과 위를 일반화 할 수 있습니다.
import contextlib
@contextlib.contextmanager
def weighted_route(compare_key=None):
yield
if compare_key is not None:
rule = app.url_map._rules[-1]
rule.match_compare_key = lambda: compare_key
# and to use
with weighted_route(compare_key):
@app.route('/<var1>/<var2>/<var3>')
def some_view(var1, var2, var3):
pass
흥미로운 몇 읽기 : [플라스크 라우팅 시스템 (http://flask.pocoo.org/docs/design/#the-routing-system)와 [WERKZEUG 라우팅 (HTTP : // WERKZEUG .pocoo.org/docs/routing/# module-werkzeug.routing). [Blueprints] (http://flask.pocoo.org/docs/blueprints/)를 사용하여 탐구하고 싶을 수도 있습니다. –