如何在python中将会话与sqlalchemy核心一起使用?

时间:2019-06-28 02:26:57

标签: python sqlalchemy

我同时使用sqlalchemy core和sqlalchemy orm,因为我想动态创建表。这是我的代码:

from sqlalchemy import create_engine,event,exc,MetaData,Table
from sqlalchemy.orm import sessionmaker,scoped_session,mapper
from sqlalchemy.ext.declarative import declarative_base

MYSQL_DB_URL = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(MYSQL_USERNAME,MYSQL_PASSWORD,MYSQL_HOST,MYSQL_PORT,MYSQL_DATABASE)

Base = declarative_base()

engine = create_engine(MYSQL_DB_URL,pool_size=300,max_overflow=0,pool_recycle=1800,pool_pre_ping=True)

DBSession = sessionmaker(bind=engine)

db_session = scoped_session(DBSession)

#orm table
class User(Base):
    ...

class CustomTable():

    def __init__(self,table_name,metadata=metadata):
        self.table = Table(table_name,metadata,
            Column('id',Integer,primary_key=True,autoincrement=True),
            extend_existing=True,
            )
        self.initial(engine=engine)

    def initial(self,engine=engine):
        #self.drop_table(engine)
        self.create_table(engine=engine)

    def create_table(self,engine=engine):
        self.table.create(engine,checkfirst=True)

    def drop_table(self,engine=engine):
        self.table.drop(engine,checkfirst=True)

if __name__ == "__main__"
    session = db_session()
    #some CRUD with session
    ...
    session.add()
    ...
    inert_data_list=[{"id":1},{"id",2}]
    #create table dynamically
    locked_t_detail_obj = CustomTable(table_name=locked_table_name)
    #insert data
    ins = locked_t_detail_obj.table.insert()
    #this line can't rollback
    session.execute(ins,inert_data_list)

    session.commit()


我想在发生异常时回滚所有更改。 我该怎么办?还是有其他解决方法?

0 个答案:

没有答案