gpt4 book ai didi

python - 使用 Flask 蓝图,如果指定了子域,如何修复 url_for 不被破坏?

转载 作者:太空狗 更新时间:2023-10-29 20:39:01 27 4
gpt4 key购买 nike

在 flask 蓝图中,我有:

frontend = Blueprint('frontend', __name__)

我的索引函数的路径是:

@frontend.route('/')
def index():
#code

这工作正常,但是,我正在尝试向路由添加一个子域,如下所示:

@frontend.route('/', subdomain='<var>')
def index(var):

但这会破坏应用程序并且浏览器会吐出(除其他外):

werkzeug.routing.BuildError
BuildError: ('frontend.index', {}, None)

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

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

To integrate applications, Flask has a hook to intercept URL build errors through Flask.build_error_handler. The url_for function results in a BuildError when the current app does not have a URL for the given endpoint and values. When it does, the current_app calls its build_error_handler if it is not None, which can return a string to use as the result of url_for (instead of url_for‘s default to raise the BuildError exception) or re-raise the exception. An example:

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

但是,我是 python(和编程)的新手,无法理解将这段代码放在哪里或发生构建错误时如何调用该函数。

任何见解将不胜感激:)

最佳答案

首先,要使用子域,您需要为 SERVER_NAME 设置一个值 configuration :

app.config['SERVER_NAME'] = 'example.net'

你有这样的观点:

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

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

关于python - 使用 Flask 蓝图,如果指定了子域,如何修复 url_for 不被破坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10542493/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com