Using flask script with filter template

I have a bulb application that uses jinja2 template filters. An example of a template filter is as follows:

@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

This works great if we have an application created before the decorator was defined, however, if we use the factory application in conjunction with the flask-script manager, then we do not have an instantiated application. For 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()

The manager accepts either an instance application or a factory application, so at first glance it seems that we can do this:

app = create_my_app()

@app.template_filter('int_date')
....

manager = Manager(app)

The problem with this solution is that the manager ignores this parameter, because the application is already configured during instance creation. So, how should someone use template filters along with a flask extension script?

+4
2

. core say core/filters.py.

, app_template_filter template_filter. , factory.

:

β”œβ”€β”€ 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

+7

, , jinja. , factory jinja_env. factory, :

def format_datetime(date):
    if date:
        return utc_time.localize(date).astimezone(london_time).strftime('%Y-%m-%d %H:%M')
    else:
        return date

def create_app(production=False):
    app = Flask(__name__)
    ....

    # Register Jinja2 filters
    app.jinja_env.filters['datetime'] = format_datetime

manager = Manager(create_app)
...
+1

Source: https://habr.com/ru/post/1618999/


All Articles