使用Flask蓝图,如果指定了子域,如何修复url_for?

chr*_*kso 8 python routes flask

在烧瓶蓝图中,我有:

frontend = Blueprint('frontend', __name__)
Run Code Online (Sandbox Code Playgroud)

和我的索引功能的路线是:

@frontend.route('/')
def index():
  #code
Run Code Online (Sandbox Code Playgroud)

这工作正常但是,我试图在路由中添加子域,如下所示:

@frontend.route('/', subdomain='<var>')
def index(var):
Run Code Online (Sandbox Code Playgroud)

但这打破了应用程序,浏览器吐出(除其他外):

werkzeug.routing.BuildError
BuildError: ('frontend.index', {}, None)
Run Code Online (Sandbox Code Playgroud)

我的代码在url_for('frontend.index')中的几个地方调用frontend.index

当我包含子域时,如何让url_for工作?在http://flask.pocoo.org/docs/api/下,我能找到的文件中唯一可能与之相关的内容是:

为了集成应用程序,Flask有一个钩子来拦截通过Flask.build_error_handler拦截URL构建错误.当前应用程序没有给定端点和值的URL时,url_for函数会导致BuildError.如果是这样,current_app会调用它的build_error_handler,如果它不是None,它可以返回一个字符串,用作url_for的结果(而不是url_for的默认值引发BuildError异常)或重新引发异常.一个例子:

def external_url_handler(error, endpoint, **values):
    "Looks up an external URL when `url_for` cannot build a URL."
    # This is an example of hooking the build_error_handler.
    # Here, lookup_url is some utility function you've built
    # which looks up the endpoint in some external URL registry.
    url = lookup_url(endpoint, **values)
    if url is None:
        # External lookup did not have a URL.
        # Re-raise the BuildError, in context of original traceback.
        exc_type, exc_value, tb = sys.exc_info()
        if exc_value is error:
            raise exc_type, exc_value, tb
        else:
            raise error
    # url_for will use this result, instead of raising BuildError.
    return url

app.build_error_handler = external_url_handler
Run Code Online (Sandbox Code Playgroud)

但是,我是python(和编程)的新手,并且无法理解我将放置此代码的位置,或者在发生builder错误时如何调用该函数.

任何见解将不胜感激:)

Sim*_*pin 13

首先,要使用子域,您需要为SERVER_NAME 配置赋值:

app.config['SERVER_NAME'] = 'example.net'
Run Code Online (Sandbox Code Playgroud)

你有这样的观点:

frontend = Blueprint('frontend', __name__)
@frontend.route('/', subdomain='<var>')
def index(var):
    return ...
Run Code Online (Sandbox Code Playgroud)

为了重建此视图的URL,Flask需要var的值.url_for('frontend.index')将失败,因为它没有足够的值.使用上述SERVER_NAME,url_for('frontend.index', var='foo')将返回http://foo.example.net/.


小智 9

添加蓝图名称url_for.例:

url_for('pay_sermepa.sermepa_cancel', _external=True)
Run Code Online (Sandbox Code Playgroud)
  • pay_sermepa:蓝图名称
  • sermepa_cancel:路线