多线程scoped_session中的SQLAlchemy
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程scoped_session中的SQLAlchemy相关的知识,希望对你有一定的参考价值。
我试图在多线程环境中使用SQLAlchemy,但我得到奇怪的错误。情况如下:
线程1启动所有SQLAlchemy对象(Engine,Models,scoped_session等)
然后,线程2尝试使用scoped_session对象在数据库上进行查询。不幸的是,从线程2错误被抛出。
我创建了一个简单的测试用例来说明我想要实现的目标:
import sqlalchemy
from sqlalchemy import Column, Integer, String, Boolean, desc, asc, func
from sqlalchemy import create_engine
sqlEngine = create_engine('sqlite:///:memory:',echo=False)
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class SimpleTable(Base):
__tablename__ = 'SimpleTable'
orderID = Column(Integer, primary_key=True)
field = Column(Integer)
def __repr__(self):
return "<Simple Table: %s>" % self.field
session_factory = sessionmaker(bind=sqlEngine)
Session = scoped_session(session_factory)
Base.metadata.create_all(sqlEngine)
for i in xrange(10):
var = SimpleTable(field=10)
Session.add(var)
Session.query(SimpleTable).all()
Session.commit()
from threading import Thread
class TestThread(Thread):
def run(self):
print "Running test thread..."
try:
print 'Grabbing data from thread:'+str(Session.query(SimpleTable).all())
except BaseException as e:
print e
print "Done running test thread..."
TestThread().start()
print 'Grabbing data outside thread:'+str(Session.query(SimpleTable).all())
这是带有错误消息的输出:
Running test thread...
(OperationalError) no such table: SimpleTable u'SELECT "SimpleTable"."orderID" AS "SimpleTable_orderID", "SimpleTable".field AS "SimpleTable_field"
FROM "SimpleTable"' ()
Done running test thread...
Grabbing data outside thread:[<Simple Table: 10>, <Simple Table: 10>, <Simple Table: 10>, <Simple Table: 10>, <Simple Table: 10>, <Simple Table: 10>, <Simple Table: 10>, <Simple Table: 10>, <Simple Table: 10>, <Simple Table: 10>]
该表因某种原因不存在。我已经阅读并重读了文档以及互联网上的多个帖子,并且似乎scoped_session存在于上述的确切情况。有人可以开导我吗?
答案
我遇到了同样的情况。我怀疑“在内存中”db不支持scoped_session。当我切换到基于普通文件的数据库时,问题就消失了。
以上是关于多线程scoped_session中的SQLAlchemy的主要内容,如果未能解决你的问题,请参考以下文章
SQLAlchemy 中的 Session、sessionmaker、scoped_session
flask-sqlalchemy 和sqlalchemy的区别
关于ORM,以及Python中SQLAlchemy的sessionmaker,scoped_session