SQLAlchemy多线程应用程序中的会话处理

时间:2017-10-13 07:16:38

标签: python multithreading session sqlalchemy

我在模块级别定义我的数据模型,如

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('cx_oracle://username:password@dsn')
Session = sessionmaker(bind=engine)

... data model located on engine

然后我开始像这样的一些线程

threads = []

# start threads
for i in range(4):

    # each thread needs it own session
    thread = threading.Thread(target=fn, args=(in, ))
    thread.start()
    threads.append(thread)

# wait for threads to finish
for thread in threads:
    thread.join()

其中fn(in)是我使用session = Session()的方法,然后用于各种目的。

有了这个,我得到了各种错误,有时只会发生。它可以是

  • DatabaseError: (cx_Oracle.DatabaseError) DPI-1002: invalid OCI handle
  • DBAPIError: (sqlalchemy.exc.ResourceClosedError) This Connection is closed
  • InvalidRequestError: Session is already flushing

我真的不知道如何解决这个问题

1 个答案:

答案 0 :(得分:0)

我们的应用程序和cx_Oracle 6.x遇到了一些类似的问题,它们被更新为使用新的Oracle OCI(ODPI-C)C接口,该接口在其发布时有一些错误引用笔记。我们降级了cx_Oracle,问题就消失了。