如何使用SQLAlchemy ORM创建表?

时间:2018-12-05 05:32:43

标签: python flask sqlalchemy

我正在尝试声明性地使用SQLAlchemy创建3个表,如此处http://flask.pocoo.org/docs/1.0/patterns/sqlalchemy/所述。但是,当我运行database.py模块时,实际上从未创建过表。谁能指出我在做错什么的正确Directino?

# database.py
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine(os.environ.get('DATABASE_URL'), echo=True, 
convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                    autoflush=True,
                                     bind=engine))

Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import models
    Base.metadata.create_all(bind=engine)

if __name__ == '__main__':
    init_db()here

在models.py里面是我定义模型以创建表的地方。当我运行database.py时,我得到的输出是

$ python database.py
2018-12-05 16:26:37,551 INFO sqlalchemy.engine.base.Engine select version()
2018-12-05 16:26:37,552 INFO sqlalchemy.engine.base.Engine {}
2018-12-05 16:26:38,072 INFO sqlalchemy.engine.base.Engine select 
current_schema()
2018-12-05 16:26:38,072 INFO sqlalchemy.engine.base.Engine {}
2018-12-05 16:26:38,597 INFO sqlalchemy.engine.base.Engine SELECT CAST('test 
plain returns' AS VARCHAR(60)) AS anon_1
2018-12-05 16:26:38,597 INFO sqlalchemy.engine.base.Engine {}
2018-12-05 16:26:38,863 INFO sqlalchemy.engine.base.Engine SELECT CAST('test 
unicode returns' AS VARCHAR(60)) AS anon_1
2018-12-05 16:26:38,863 INFO sqlalchemy.engine.base.Engine {}
2018-12-05 16:26:39,383 INFO sqlalchemy.engine.base.Engine show 
standard_conforming_strings
2018-12-05 16:26:39,383 INFO sqlalchemy.engine.base.Engine {}

如您所见,没有发出任何实际的SQL命令来创建表,而我对我做错的事情不知所措。有谁对为什么不创建表有任何想法?

1 个答案:

答案 0 :(得分:0)

如果在命令行上使用flask run运行应用程序,则__name__ == '__main__'为False。因此,请删除此if语句,然后将您的数据库初始化。

此外,您可以尝试from models import Base而不只是import models