I define my Flask application using the app factory pattern. When using Flask-Script, I can pass the factory function to the Manager
. I'd like to use Flask's built-in Click CLI instead. How do I use the factory with Click?
My current code uses Flask-Script. How do I do this with Click?
from flask import Flask
from flask_script import Manager, Shell
def create_app():
app = Flask(__name__)
...
return app
manager = Manager(create_app)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role)
manager.add_command('shell', Shell(make_context=make_shell_context))
if __name__ == '__main__':
manager.run()
The
flask
command is a Click interface created withflask.cli.FlaskGroup
. Create your own group and pass it the factory function. Useapp.shell_context_processor
to add objects to the shell.Run your file instead of the
flask
command. You'll get the Click interface using your factory.Ideally, create an entry point and install your package in your env. Then you can call the script as a command. Create a
setup.py
file with at least the following.Using your own CLI is less robust than the built-in
flask
command. Because yourcli
object is defined with your other code, a module-level error will cause the reloader to fail because it can no longer import the object. Theflask
command is separate from your project, so it's not affected by errors in your module.