Using the checkbox Click CLI with factory application template

I am defining a Flask application using the factory application template. When using Flask-Script, I can pass the factory function to Manager . Instead, I would like to use the CLOCK built-in click button. How to use factory with Click?

My current code uses the Script checkbox. How to do it 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() 
+5
source share
1 answer

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.

+6
source

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


All Articles