数据库(三)为Python shell添加新的功能和使用Flask-Migrate实现数据库迁移

本文介绍了如何为Python shell添加自动导入数据库实例和模型的功能,以及如何利用Flask-Migrate进行数据库迁移。通过创建迁移仓库、编写迁移脚本,实现了在数据库模型变化时更新数据库的操作。
摘要由CSDN通过智能技术生成

为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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值