如何存储全局(url_for)URL(和其他全局变量)并在 Flask 应用程序中共享?

How to store global (url_for) URL's (and other global variables) and share across Flask application?

我有一些神社模板;每个共享一些通用的样式表和 js 资源。在 Flask 中,我使用 url_for 方法来识别每个 URL。

例如

icomoonstyle = url_for('static', filename='css/icons/icomoon/styles.css')
bootstrapstyle = url_for('static', filename='css/bootstrap.min.css')
corestyle = url_for('static',filename='css/core.min.css')

我的问题是;如何在不同的路由中共享这些变量,而不必在每个装饰器函数下重新指定上述代码?

我这样说对吗,像这样的全局任何东西都应该存储在某种数据库或内存缓存(redis、mongo 等)中? OR 是否有最佳实践方法可以在其他地方的代码中安全地存储这样的全局变量?

不,这些是静态值,它们不属于数据库或缓存;它们应该在代码中定义。

您可以通过将项目放入 Environment.globals 来使项目对所有 Jinja2 模板可用,请参阅 the docs

您可以使用 app.context_processor 将值添加到 Jinja2 环境,从而使它们直接可用于所有模板:

@app.context_processor
def provide_links():
    with app.app_context():
        return {
          "icomoonstyle": url_for('static', filename='css/icons/icomoon/styles.css'),
          "bootstrapstyle": url_for('static', filename='css/bootstrap.min.css'),
          "corestyle": url_for('static',filename='css/core.min.css')
        }

然后 所有 你的 Jinja 模板将能够使用返回字典中定义的变量:

<link rel="stylesheet" href="{{ icomoonstyle }}">

更好的是,您可以将所有样式放在一个列表中:

return {"STYLES": [
    url_for('static', filename='css/icons/icomoon/styles.css'),
    url_for('static', filename='css/bootstrap.min.css'),
    url_for('static',filename='css/core.min.css')
]}

然后遍历它们(假设你只打算在一个地方使用它们):

{% for style in STYLES %}
<link rel="stylesheet" href="{{ style }}">
{% endfor %}