在Flask-SQLAchemy中创建表

时间:2015-10-30 08:26:12

标签: python sqlalchemy flask-sqlalchemy

以下代码有效,以便创建名为users的新表:

engine = create_engine('mysql+pymysql://root:@localhost/sqlalchemy_tutorial', convert_unicode=True,echo=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()


Base = declarative_base()
from sqlalchemy import Column, Integer, String
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    email = Column(String(120), unique=True)

    def __init__(self, name=None, email=None):
        self.name = name
        self.email = email

    def __repr__(self):
        return '<User %r>' % (self.name)


Base.metadata.create_all(bind=engine)

但是下一个代码没有创建用户表,为什么?

.
├── application.py
├── flaskapp.cfg
├── models
│   ├── User.py
│   ├── __init__.py
│   └── __init__.pyc
└── requirements.txt

初始化的.py

__author__ = 'Ricardo'
from models import User;

User.py

__author__ = 'Ricardo'
from sqlalchemy import Column, Integer, String
from application import Base
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    email = Column(String(120), unique=True)

    def __init__(self, name=None, email=None):
        self.name = name
        self.email = email

    def __repr__(self):
        return '<User %r>' % (self.name)

application.py

Base = declarative_base()
Base.query = db_session.query_property()
Base = declarative_base()
import models
#import models.User
#what else?
Base.metadata.create_all(bind=engine)

0 个答案:

没有答案