Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flask-script together with template-filter

Tags:

python

flask

I have a flask application which uses jinja2 template filters. An example of 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 fine if we have an app instantiated before a decorator is defined, however if we are using an app factory combined with flask-script manager, then we don't have an instantiated app. 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()

Manager accepts either an instantiated app or an app factory, so at first glance it appears 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 then ignores the option, since the app has already been configured during instantiation. So how is someone supposed to use template filters together with the flask-script extension?

like image 429
Angelos Avatar asked Dec 18 '22 21:12

Angelos


1 Answers

This is where blueprints come into play. I would define a blueprint core and put all my custom template filters in say core/filters.py.

To register filters to an application in flask when using blueprints you need to use app_template_filter instead of template_filter. This way you can still use the decorator pattern to register filters and use the application factory approach.

A typical directory layout for an application using blueprint might look something like:

├── 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              

For a minimal working example of this approach see: https://github.com/iiSeymour/app_factory

like image 126
Chris Seymour Avatar answered Jan 04 '23 13:01

Chris Seymour