我正在学习sqlalchemy
。
这是我的初始代码:
用户.py
from sqlalchemy import Column, Integer, Sequence, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer,Sequence('user_seq'), primary_key=True)
username = Column(String(50), unique=True)
fullname = Column(String(150))
password = Column(String(50))
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password
主文件
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from user import User
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
if __name__ == '__main__':
engine = create_engine('mysql://root:password@127.0.0.1:3306/test', echo=True)
Base.metadata.create_all(engine, checkfirst=True)
Session = sessionmaker(bind=engine)
session = Session()
ed_user = User('ed', 'Ed Jones', 'edspassword')
session.add(ed_user)
session.commit()
当我运行main.py时,它不会自动创建表并在session.commit()
.
此外,当我将行移动Base = declarative_base()
到任何不同的模块并在main.py和user.pyBase
中使用相同的变量时- 它会创建表。
我的问题:“什么是declarative_base
”?