我有一个使用 jinja2 模板过滤器的 flask 应用程序。模板过滤器示例如下:
@app.template_filter('int_date')
def format_datetime(date):
if date:
return utc_time.localize(date).astimezone(london_time).strftime('%Y-%m-%d %H:%M')
else:
return date
如果我们在定义装饰器之前实例化了一个应用程序,这会很好地工作,但是如果我们使用一个结合了 flask-script 管理器的应用程序工厂,那么我们就没有一个实例化的应用程序。对于 example :
def create_my_app(config=None):
app = Flask(__name__)
if config:
app.config.from_pyfile(config)
return app
manager = Manager(create_my_app)
manager.add_option("-c", "--config", dest="config", required=False)
@manager.command
def mycommand(app):
app.do_something()
Manager 接受一个实例化的应用程序或一个应用程序工厂,所以乍一看我们可以这样做:
app = create_my_app()
@app.template_filter('int_date')
....
manager = Manager(app)
此解决方案的问题在于管理器随后会忽略该选项,因为应用程序已在实例化期间进行了配置。那么人们应该如何将模板过滤器与 flask-script 扩展一起使用呢?
最佳答案
这就是蓝图发挥作用的地方。我会定义一个蓝图 core
并将我所有的自定义模板过滤器放在 core/filters.py
中。
要在使用蓝图时将过滤器注册到 Flask 中的应用程序,您需要使用 app_template_filter
而不是 template_filter
.这样您仍然可以使用装饰器模式来注册过滤器并使用应用程序工厂方法。
使用蓝图的应用程序的典型目录布局可能类似于:
├── app
│ ├── blog
│ │ ├── __init__.py # blog blueprint instance
│ │ └── routes.py # core filters can be used here
│ ├── core
│ │ ├── __init__.py # core blueprint instance
│ │ ├── filters.py # define filters here
│ │ └── routes.py # any core views are defined here
│ └── __init__.py # create_app is defined here & blueprint registered
└── manage.py # application is configured and created here
有关此方法的最小工作示例,请参阅:https://github.com/iiSeymour/app_factory
关于python - 将 flask 脚本与模板过滤器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34149452/