【问题标题】:Setting global attributes in Flask framework在 Flask 框架中设置全局属性
【发布时间】:2012-08-27 13:51:25
【问题描述】:

我正在使用 Flask/Python 开发一个小型 Web 项目。这是一个没有数据库的简单客户端应用程序。

我想将 REST 服务地址设置为全局属性,但还没想好怎么做。

我知道可以像这样在flask.config中设置属性:

app = Flask(__name__)
app.config['attribute_name'] = the_service_address

但蓝图模块无法访问“app”对象。

非常感谢您的宝贵时间。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    在请求上下文中(即在视图/处理程序中),您可以访问 current_app 上的配置

    from flask import current_app
    current_app.config['attribute_name']
    

    【讨论】:

    • 请注意,根据问题,这在全局范围内不起作用 - 尝试在请求上下文之外访问 current_app 将导致 RuntimeError: Working outside of application context.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 2016-02-20
    • 2012-11-13
    • 2021-07-31
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多