如何使用声明性基础连接Flask中的迁移?

时间:2016-06-16 15:18:56

标签: flask flask-sqlalchemy

我在flask_sqlalchemy中使用声明性Base。在我的database.py文件中,我有以下内容:

from sqlalchemy import create_engine
# from sqlalchemy.orm import scoped_session, sessionmaker
# from sqlalchemy.ext.declarative import declarative_base
# from flask_sqlalchemy import SQLAlchemy

# engine = create_engine("postgresql://postgres:@localhost/video_comparisons", convert_unicode=True)
# db_session = scoped_session(sessionmaker(autocommit=False,
#                                          autoflush=False,
#                                          bind=engine))
# Base = declarative_base()
# Base.query = db_session.query_property()

# Session = sessionmaker(bind = engine)

# db = SQLAlchemy()

# def init_db():
#     # import all modules here that might define models so that
#     # they will be registered properly on the metadata.  Otherwise
#     # you will have to import them first before calling init_db()
#     import yourapplication.models
#     Base.metadata.create_all(bind=engine)

现在,我的每个模型都从database.py导入Base对象。这避免了循环导入。

接下来,我尝试连接Flask迁移模块,它应该像这样工作:

db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

如您所见,我需要将db传递给Migrate构造函数。但我没有db对象,因为我使用声明性Base,而不是使用db = SQLAlchemy(app)创建它。

最好的方法是什么?在文档中,我无法看到如何使用此语法将Migrate对象连接到数据库。

谢谢, 路易丝

2 个答案:

答案 0 :(得分:0)

您必须从database.py导入db对象:)

答案 1 :(得分:0)

#timepass.py
from database import Base, metadata
from sqlalchemy import Table
class Timepass(Base):
    __table__ = Table('timepass', metadata, autoload=True)
#user.py
from project import db
class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(15), unique=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(80))