一つの方法は、登録されたルールのmatch_compare_key()
方法をなりすましによるソートアルゴリズムのルールをカンニングすることです。このハックは、青写真ではなく、app.route()
(Flaskオブジェクト)で直接登録されたルートでのみ機能することに注意してください。 Blueprintsのルートは、主なアプリケーションでの青写真の登録時にのみグローバルURLマップに追加され、生成されたルールを変更するのは難しい作業です。
# 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/)を使って探検してみることもできます。 –