9

エンドポイントへの参照とすべての引数の辞書を取得するために、Flask 内で URL を解決する適切な方法は何でしょうか?

'/user/nick'例を提供するために、このルートを考えると、解決したいと思いますprofile, {'username': 'nick'}:

@app.route('/user/<username>')
def profile(username): pass

これまでの私の調査から、Flask のすべてのルートは に保存されapp.url_mapます。マップはwerkzeug.routing.Mapmatch()のインスタンスであり、原則として私が探していることを行うメソッドがあります。ただし、そのメソッドはクラスの内部にあります。

4

3 に答える 3

10

これは、私がこの目的のためにハッキングしたもので、それを見てurl_for()元に戻しました:

from flask.globals import _app_ctx_stack, _request_ctx_stack
from werkzeug.urls import url_parse

def route_from(url, method = None):
    appctx = _app_ctx_stack.top
    reqctx = _request_ctx_stack.top
    if appctx is None:
        raise RuntimeError('Attempted to match a URL without the '
                           'application context being pushed. This has to be '
                           'executed when application context is available.')

    if reqctx is not None:
        url_adapter = reqctx.url_adapter
    else:
        url_adapter = appctx.url_adapter
        if url_adapter is None:
            raise RuntimeError('Application was not able to create a URL '
                               'adapter for request independent URL matching. '
                               'You might be able to fix this by setting '
                               'the SERVER_NAME config variable.')
    parsed_url = url_parse(url)
    if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name:
        raise NotFound()
    return url_adapter.match(parsed_url.path, method)

このメソッドの戻り値はタプルで、最初の要素はエンドポイント名で、2 番目の要素は引数を持つ辞書です。

私はそれを広範囲にテストしていませんが、すべての場合にうまくいきました。

于 2013-10-28T14:17:29.230 に答える
2

回答が遅れていることはわかっていますが、同じ問題に遭遇し、それを取得するためのより簡単な方法を見つけました: request.view_args. 例えば:

私の見解では:

@app.route('/user/<username>')
def profile(username): 
    return render_template("profile.html")

: {{ request.view_args profile.html}}

URLhttp://localhost:4999/user/samにアクセスすると、次のようになります{'username': u'sam'}

でビューを取得した関数の名前を取得することもできますrequest.endpoint

于 2015-08-20T05:25:35.283 に答える