The flask command is a click interface created using flask.cli.FlaskGroup . Create your own group and pass the factory function to it. Use app.shell_context_processor to add objects to the shell.
from flask import Flask from flask.cli import FlaskGroup from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(script_info=None): app = Flask(__name__) db.init_app(app) ... @app.shell_context_processor def shell_context(): return {'app': app, 'db': db} return app cli = FlaskGroup(create_app=create_app) @cli.command def custom_command(): pass if __name__ == '__main__': cli()
Run the file instead of the flask command. You will get the Click interface with the factory.
FLASK_DEBUG=1 python app.py run
Ideally create an entry point and install your package in env. Then you can invoke the script as a command. Create a setup.py , at least the following.
project/ app/ __init__.py setup.py
from setuptools import setup, find_packages setup( name='my_app', version='1.0.0', packages=find_packages(), entry_points={ 'console_scripts': [ 'app=app:cli', ], }, )
pip install -e /path/to/project FLASK_DEBUG=1 app run
Using the native CLI is less reliable than the flask built-in command. Since your cli object cli defined by your other code, a module-level error will result in a reboot failure because it can no longer import the object. The flask command is different from your project, so it is not affected by errors in your module.
source share