I am learning sqlalchemy
.
Here is my initial code :
user.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
main.py
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:[email protected]: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()
When I run main.py, it won't create tables automatically and gives me an exception on session.commit()
.
Also, when I move line Base = declarative_base()
to any different module and use the same Base
variable in main.py and in user.py - it creates the table.
My question: "What is declarative_base
" ?
question from:
https://stackoverflow.com/questions/15175339/sqlalchemy-what-is-declarative-base 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…