问题描述
我使用应用程序工厂模式定义我的Flask应用程序。当使用Flask-Script时,我可以将工厂函数传递给
flask 命令是使用 flask.cli创建的Click接口.FlaskGroup 。创建自己的组并将其传递给工厂功能。使用 app.shell_context_processor 将对象添加到shell。
from flask从flask.cli中导入Flask
从flask.sqlalchemy中导入FlaskGroup
SQLAlchemy
$ b db = SQLAlchemy()
$ b $ def shell_context():
返回{'app':app,'db':db}
$ b $ def create_app(script_info = None):
app = Flask(__ name__)
db.init_app(app)
...
app.shell_context_processor(shell_context)
返回应用程序
$ b cli = FlaskGroup(create_app = create_app)
@cli。命令
def custom_command():
传递
$ b $如果__name__ =='__main__':
cli()
/ pre>
运行您的文件而不是 flask 命令。你会得到你的工厂的Click界面。
FLASK_DEBUG = 1 python app.py run
理想情况下,创建一个入口点并将其安装到您的环境中。然后,您可以将该脚本作为命令调用。创建一个 setup.py 文件,至少包含以下内容:
项目/
应用程式/
__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':[$ b $'app = app:cli',
$ bpip install -e / path / to / project
FLASK_DEBUG = 1 app run
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 with flask.cli.FlaskGroup. Create your own group and pass it the factory function. 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 shell_context(): return {'app': app, 'db': db} def create_app(script_info=None): app = Flask(__name__) db.init_app(app) ... app.shell_context_processor(shell_context) return app cli = FlaskGroup(create_app=create_app) @cli.command def custom_command(): pass if __name__ == '__main__': cli()Run your file instead of the flask command. You'll get the Click interface using your factory.
FLASK_DEBUG=1 python app.py runIdeally, 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.
project/ app/ __init__.py setup.pyfrom 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
这篇关于将Flask的Click CLI与应用程序工厂模式一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!