sqlalchemy orm 中的 crud 函数
Posted
技术标签:
【中文标题】sqlalchemy orm 中的 crud 函数【英文标题】:crud functions in sqlalchmey orm 【发布时间】:2019-03-11 10:19:20 【问题描述】:所以我试图在我的代码上实现 CRUD 函数,所以我试图先创建一个会话,但它一直给我一个错误“引擎未定义”所以我试图定义它,但我一直收到同样的错误.该代码正在使用 sqlalchemy ORM 创建一个数据库 3 个表(用户、帐户、位置)。我做错了什么?
from sqlalchemy import create_engine, Column, Integer, Boolean, String, ForeignKey, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.query.Query
Session = sessionmaker(bind=engine)
Base = declarative_base()
class User(Base):
__tablename__ = "user"
id = Column('id',Integer,primary_key=True , autoincrement=True)
username = Column('username',String , unique=True)
admin = Column('admin',Boolean )
password = Column('password' , String)
email = Column('email' , String , unique=True)
p_id = Column(Integer , ForeignKey('place.id'))
googleassist = Column('googleassist' , String)
account = relationship("Account", ## Cascade to delete associated account
back_populates='user', ## if that user was deleted.
cascade='all, delete-orphan')
class Account(Base):
__tablename__ = "account"
id = Column('id', Integer,primary_key=True,autoincrement=True)
user_id = Column(Integer , ForeignKey('user.id'))
class Place(Base):
__tablename__ = "place"
id = Column('id', Integer,primary_key=True,autoincrement=True)
p_location = Column('p_location' , String)
h_id = Column('h_id',Integer)
Session.configure(bind=engine)
engine = create_engine('sqlite:///withServer.db')
Base.metadata.create_all(engine)
session = Session(engine)
#creating objects
u1=User( id = '1' ,
username = 'ali',
admin = '1',
password = 'pass',
email = 'haifa@gmail.com'
)
session.add(u1)
session.commit()
#update
i = session.query(User)
i.password = 'passtoo'
session.add(i)
session.commit()
#delete
i = session.query(Account).filter(Account.id == '1').one()
session.delete(i)
session.commit()
【问题讨论】:
【参考方案1】:确实你只是使用engine
而不先定义它:
Session = sessionmaker(bind=engine)
您需要在该行之前定义engine
。移动
engine = create_engine('sqlite:///withServer.db')
在第一次使用engine
之前。
【讨论】:
以上是关于sqlalchemy orm 中的 crud 函数的主要内容,如果未能解决你的问题,请参考以下文章