在使用带Flask的应用程序工厂时,如何在“app”上放置装饰器?

2024-06-13 17:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的应用程序定义一些全局常量,并且发现这可以通过一个修饰为@app.context_processor的函数来完成。你知道吗

但是,问题是我没有app变量。我的应用程序使用一个应用程序工厂,我希望保持这种方式。有没有其他方法将函数注册为我的应用程序的context_processor?你知道吗

我看到的一个选项是将decorator应用于每个Blueprint,而不是应用于应用程序。这是我想避免的,因为它会导致大量的重复代码。你知道吗


Tags: 方法函数代码app应用程序工厂选项方式
1条回答
网友
1楼 · 发布于 2024-06-13 17:06:28

问题是工厂没有app对象。你有一个create_app函数来创建应用程序。你知道吗

因此,要安装上下文处理器,可以使用create_app本身

def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_pyfile(config_filename)

    from yourapplication.model import db
    db.init_app(app)

    from yourapplication.context_processor import myprocessor
    app.context_processor(myprocessor)

    from yourapplication.views.frontend import frontend
    app.register_blueprint(frontend)

    return app

你也可以用同样的函数应用程序类型文件(无论在何处编写create\u app()函数)。在这种情况下,您可以简单地注册上下文处理器而不导入它。你知道吗

另一种方法是在如下所示的蓝图中进行

Flask context processors functions

from flask import Blueprint

thingy = Blueprint("thingy", __name__, template_folder='templates')

@thingy.route("/")
def index():
  return render_template("thingy_test.html")

@thingy.context_processor
def utility_processor():
  def format_price(amount, currency=u'$'):
    return u'{1}{0:.2f}'.format(amount, currency)
  return dict(format_price=format_price)

相关问题 更多 >