web-dev-qa-db-ja.com

フラスコ:現在のルートを取得

Flaskで、同じ機能に対して複数のルートがある場合、現在どのルートが使用されているかをどのように確認できますか?

例えば:

@app.route("/antitop/")
@app.route("/top/")
@requires_auth
def show_top():
    ....

どうすればわかりますか、今は/top/ または /antitop/

[〜#〜] update [〜#〜]

request_pathリクエストはかなり複雑になる可能性があり、関数内でルーティングロジックを繰り返す必要があるため、使用しません。私はurl_ruleそれが最高のもの。

45
Igor Chubin

どのルートがビューをトリガーしたかを確認する最も「ゆるい」方法は、 request.url_rule

from flask import request

rule = request.url_rule

if 'antitop' in rule.rule:
    # request by '/antitop'

Elif 'top' in rule.rule:
    # request by '/top'
45
thkang

request.path

from flask import request

...

@app.route("/antitop/")
@app.route("/top/")
@requires_auth
def show_top():
    ... request.path ...
58
falsetru

別のオプションは、エンドポイント変数を使用することです:

@app.route("/api/v1/generate_data", methods=['POST'], endpoint='v1')
@app.route("/api/v2/generate_data", methods=['POST'], endpoint='v2')
def generate_data():
    version = request.endpoint
    return version
26
marcinkuzminski

ルートごとに異なる動作が必要な場合は、2つの関数ハンドラーを作成するのが適切です。

@app.route("/antitop/")
@requires_auth
def top():
    ...

@app.route("/top/")
@requires_auth
def anti_top():
    ...

場合によっては、構造が理にかなっています。ルートごとに値を設定できます。

@app.route("/antitop/", defaults={'_route': 'antitop'})
@app.route("/top/", defaults={'_route': 'top'})
@requires_auth
def show_top(_route):
    # use _route here
    ...
7
iurisilvio

重要な状況がある場合、そもそも同じ機能を使用すべきではないようです。それを2つの個別のハンドラーに分割し、それぞれが共有コードの共通のフィクションを呼び出します。

0
Daniel Roseman