为Python shell添加新的功能
每次启动shell会话都得导入数据库实例和模型,我可以让Flask-Scripts的shell命令自动导入特定的对象
为shell命令添加一个上下文
from flask_script import Manager, Shell
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role)
manager.add_command("shell", Shell(make_context=make_shell_context))
###manage.add_command("shell命令名",Shell(make_context回调函数=make_shell_context函数))
若想把对象添加到导入列表中,我们要为shell命令注册一个make_context回调函数,make_shell_context()函数注册了程序,数据库实例以及模型,因此这些对象可以直接导入shell。
(venv) C:\Users\Geek Lee\Geek-Lee.github.io>python hello.py shell
C:\Users\GEEKLE~1\GEEK-L~1.IO\venv\lib\site-packages\flask_sqlalchemy\__init__.p
y:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and
will be disabled by default in the future. Set it to True to suppress this war
ning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and wi
ll be disabled by default in the future. Set it to True to suppress this warnin
g.')
>>> app
<Flask 'hello'>
>>> db
<SQLAlchemy engine='sqlite:///C:\\Us