python - 将 flask 脚本与模板过滤器一起使用

标签 python flask

我有一个使用 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/

相关文章:

python - 为单个单元测试用例更改 celery 设置 task_always_eager

python - Flask-OAuthlib 从 token 处理程序获取 access_token

python - 如何在flask中重新加载python模块?

python打开文本文件,每个字符之间有一个空格

python - PyQT 和 Visual Studio 2010

python - 在哪里可以找到 Azure Cosmos DB 中的 masterekey 访问的访问日志

python - flask 属性错误 : 'HTMLString' object has no attribute '__call__'

python - Flask 网络服务器的外部可见性问题

具有多处理功能的 Python pint 模块

python - (centos6.6) 更新python2.7.3之前,是python 2.6.6。运行 pybot --version 时出现错误