Flask shell - 如何为 url_for _external=True 设置服务器名称?

Flask shell - how to set server name for url_for _external=True?

我在 docker 容器中有一个烧瓶应用程序 运行。一切正常,除非我想在来自烧瓶 shell 的同一个 docker 容器中做一些手动工作。问题是 url_for(x, _external=True) 总是 returns https://localhost,不管我如何尝试在 shell 中设置服务器名称。 我显然已经尝试将 SERVER_NAME 设置为不变。

$ python manage.py shell
>>> from flask import current_app
>>> current_app.config['SERVER_NAME'] = 'example.com'
>>> from app import models
>>> models.Registration.send_registration(id=123)

神社模板有: {{ url_for('main.index', _external=True, _scheme='https') }}

生成: https://localhost

我想得到: https://example.com

我正在使用 Flask 0.11、Werkzeug 0.11.10 和 Jinja2 2.8

您的应用程序使用创建应用程序上下文时定义的 SERVER_NAME

如果您想在 shell 中执行此操作,您可以在设置 SERVER_NAME 后创建测试请求上下文。

>>> from flask import current_app, url_for
>>> current_app.config['SERVER_NAME'] = 'example.com'
>>> with current_app.test_request_context():
...     url = url_for('index', _external=True)
...
>>> print url
http://example.com/

我们可以深入Flask代码来理解它。

Flask url_for 使用 appctx.url_adapter to build this URL. This url_adapter is defined when the AppContext is initialized, and it happens when the shell is started. It calls the app.create_url_adapter 并使用定义的 SERVER_NAME.

此解决方案与已经介绍的解决方案非常相似,只是需要的步骤更少:

from flask import current_app, url_for

with current_app.test_request_context('localhost.com'):
    url = url_for('index')
    ...

这样就不需要设置配置 SERVER_NAME 因为我们在现场注入 reqctx 以便 url_for 可以正确构建路径。对于我的情况,我想要一个相对路径,所以我不需要添加属性 _external.