我正在关注Miguel 的本教程。有一个迁移脚本来创建迁移。db_migrate.py
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
migration = SQLALCHEMY_MIGRATE_REPO + ('/versions/%03d_migration.py' % (v+1))
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec(old_model, tmp_module.__dict__)
script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, tmp_module.meta, db.metadata)
open(migration, "wt").write(script)
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('New migration saved as ' + migration)
print('Current database version: ' + str(v))
并用于升级它拥有的数据库db_upgrade.py
。
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('Current database version: ' + str(v))
现在每次我运行db_migrate.py
它都会创建一个包含相同代码的迁移文件:
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadata
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
如果我运行db_upgrade.py
,它只会增加migrate_version
数据库中表中的迁移版本,但不会创建新表。我需要手动编辑迁移文件来创建表吗?
配置:
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@localhost/microblog'
SQLALCHEMY_MIGRATE_REPO = os.path.join(BASEDIR, 'db_repository')
这是我的models.py
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(35), index = True, unique = True)
email = db.Column(db.String(255), index = True, unique = True)
password = db.Column(db.String(255), index = False, unique = False)
posts = db.relationship('Post', backref='author', lazy='dynamic')
def __repr__(self):
return '< User %r>' % (self.username)
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post %r>' % (self.body)