您的位置:首页 > 运维架构 > Shell

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

2016-09-19 19:11 821 查看

为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:\\Users\\Geek Lee\\Geek-Lee.github.io\\data.sqli
te'>
>>> User
<class '__main__.User'>


使用Flask-Migrate实现数据库迁移

开发数据库时,有时需要修改数据库模型,修改完后还得更新数据库。

仅当数据库表不存在时,Flask-SQLAlchemy才会根据模型进行创建。

更新表的最好办法是使用数据库迁移框架。*Flask程序可使用Flask-Migrate扩展。这个扩展对Alembic做了轻量级包装,并集成在Flask-Script中,所有操作都通过Flask-Script命令完成*。

(venv) C:\Users\Geek Lee\Geek-Lee.github.io>pip install flask-migrate

Installing collected packages: Mako, python-editor, alembic, flask-migrate
Successfully installed Mako-1.0.4 alembic-0.8.8 flask-migrate-2.0.0 python-editor-1.0.1


from flask_migrate import Migrate,MigrateCommand
...
migrate = Migrate(app, db)
...
manager.add_command('db', MigrateCommand)
...


Flask-Migrate提供一个MigrateCommand类,可附加到Flask-Script的manager对象上,在这个例子中,MigrateCommand类使用db命令附加。ps:上个命令附加到shell上了。

创建迁移仓库

报错了!!!

(venv) C:\Users\Geek Lee\Geek-Lee.github.io>python hello.py db init
C:\Users\GEEKLE~1\GEEK-L~1.IO\venv\lib\site
-packages\flask_sqlalchemy\__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True to suppress this warnin
g.')
Creating directory C:\Users\Geek Lee\Geek-Lee.github.io\migrations ... done
Creating directory C:\Users\Geek Lee\Geek-Lee.github.io\migrations\versions ...
done
Generating C:\Users\Geek Lee\Geek-Lee.github.io\migrations\alembic.ini ... done
Generating C:\Users\Geek Lee\Geek-Lee.github.io\migrations\env.py ... done
Generating C:\Users\Geek Lee\Geek-Lee.github.io\migrations\README ... done
Generating C:\Users\Geek Lee\Geek-Lee.github.io\migrations\script.py.mako ... do
ne
Please edit configuration/connection/logging settings in 'C:\\Users\\Geek Lee\\G
eek-Lee.github.io\\migrations\\alembic.ini' before proceeding.


直白的warning:

把sql-alchemy在init.py里的SQLALCHEMY_TRACK_MODIFICATIONS改为True就行了

track_modifications=app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True)


以前默认是True的,版本更新后默认是None了

SQLALCHEMY_TRACK_MODIFICATIONS:如果设置成 True (默认情况),Flask-SQLAlchemy将会追踪对象的修改并且发送信号。这需要额外的内存, 如果不必要的可以禁用它。

千万不要改错地方了!!!

千万不要改错地方了!!!

千万不要改错地方了!!!

更改代码的位置为下面这段

def init_app(self, app):
"""This callback can be used to initialize an application for the
use with this database setup.  Never use a database in the context
of an application not initialized that way or connections will
leak.
"""
app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite://')
app.config.setdefault('SQLALCHEMY_BINDS', None)
app.config.setdefault('SQLALCHEMY_NATIVE_UNICODE', None)
app.config.setdefault('SQLALCHEMY_ECHO', False)
app.config.setdefault('SQLALCHEMY_RECORD_QUERIES', None)
app.config.setdefault('SQLALCHEMY_POOL_SIZE', None)
app.config.setdefault('SQLALCHEMY_POOL_TIMEOUT', None)
app.config.setdefault('SQLALCHEMY_POOL_RECYCLE', None)
app.config.setdefault('SQLALCHEMY_MAX_OVERFLOW', None)
app.config.setdefault('SQLALCHEMY_COMMIT_ON_TEARDOWN', False)
track_modifications = app.config.setdefault(
'SQLALCHEMY_TRACK_MODIFICATIONS', True)######这个位置


运行成功的结果:

(venv) C:\Users\Geek Lee\Geek-Lee.github.io>python hello.py db init
Creating directory C:\Users\Geek Lee\Geek-Lee.github.io\migrations ... done
Creating directory C:\Users\Geek Lee\Geek-Lee.github.io\migrations\versions ...
done
Generating C:\Users\Geek Lee\Geek-Lee.github.io\migrations\alembic.ini ... done
Generating C:\Users\Geek Lee\Geek-Lee.github.io\migrations\env.py ... done
Generating C:\Users\Geek Lee\Geek-Lee.github.io\migrations\README ... done
Generating C:\Users\Geek Lee\Geek-Lee.github.io\migrations\script.py.mako ... do
ne
Please edit configuration/connection/logging settings in 'C:\\Users\\Geek Lee\\G
eek-Lee.github.io\\migrations\\alembic.ini' before proceeding.


这个init子命令创建迁移仓库(migrations文件夹),所有迁移脚本都放在里面。

数据库迁移仓库中的文件要和其他的文件一起纳入版本控制。

创建迁移脚本

migrate子命令用来自动创建迁移脚本:

(venv) C:\Users\Geek Lee\Geek-Lee.github.io>python hello.py db migrate -m "initi
al migration"
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.env] No changes in schema detected.


更新数据库

(venv) C:\Users\Geek Lee\Geek-Lee.github.io>python hello.py db upgrade
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: