我有一个Flask视图,它使用SQLAlchemy查询和显示一些博客文章。我正在使用mod_wsgi运行我的应用程序。此视图在我第一次进入页面时起作用,但下次返回500错误。回溯显示错误ProgrammingError: SQLite objects created in a thread can only be used in that same thread.
为什么我收到此错误以及如何解决?
views.py
engine = create_engine('sqlite:////var/www/homepage/blog.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
@app.route('/blog')
@app.route('/blog.html')
def blog():
entrys = session.query(Entry).order_by(desc(Entry.timestamp)).all()
return render_template('blog.html', blog_entrys = entrys)
models.py
:
class Entry(Base):
__tablename__ = 'entry'
id = Column(Integer, primary_key = True)
title = Column(String(100), nullable = False)
body = Column(String, nullable = False)
timestamp = Column(DateTime, nullable = False)
featured = Column(Boolean, nullable = False)
comments = relationship('Comment')
def is_featured(self):
return self.featured
class Comment(Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key = True)
entry_id = Column(Integer, ForeignKey('entry.id'))
text = Column(String(500), nullable = False)
name = Column(String(80))
engine = create_engine('sqlite:////var/www/homepage/blog.db')
Base.metadata.create_all(engine)
Exception on /blog.html [GET]
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/flask/app.py", line 861, in wsgi_app
rv = self.dispatch_request()
File "/usr/lib/python2.6/dist-packages/flask/app.py", line 696, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/var/www/homepage/webserver.py", line 38, in blog
entrys = session.query(Entry).order_by(desc(Entry.timestamp)).all()
File "/usr/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 1453, in all
return list(self)
File "/usr/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 1565, in __iter__
return self._execute_and_instances(context)
File "/usr/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 1570, in _execute_and_instances
mapper=self._mapper_zero_or_none())
File "/usr/lib/python2.6/dist-packages/sqlalchemy/orm/session.py", line 735, in execute
clause, params or {})
File "/usr/lib/python2.6/dist-packages/sqlalchemy/engine/base.py", line 1157, in execute
params)
File "/usr/lib/python2.6/dist-packages/sqlalchemy/engine/base.py", line 1235, in _execute_clauseelement
parameters=params
File "/usr/lib/python2.6/dist-packages/sqlalchemy/engine/base.py", line 1348, in __create_execution_context
None, None)
File "/usr/lib/python2.6/dist-packages/sqlalchemy/engine/base.py", line 1343, in __create_execution_context
connection=self, **kwargs)
File "/usr/lib/python2.6/dist-packages/sqlalchemy/engine/default.py", line 381, in __init__
self.cursor = self.create_cursor()
File "/usr/lib/python2.6/dist-packages/sqlalchemy/engine/default.py", line 523, in create_cursor
return self._connection.connection.cursor()
File "/usr/lib/python2.6/dist-packages/sqlalchemy/pool.py", line 383, in cursor
c = self.connection.cursor(*args, **kwargs)
ProgrammingError: (ProgrammingError) SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140244498364160 and this is thread id 140244523542272 None [{}]
答案 0 :(得分:24)
从this SO answer获取提示我搜索了SA文档,发现你可以这样做:
engine = create_engine('sqlite:////var/www/homepage/blog.db?check_same_thread=False')
scoped_session
在我的案例中并不合适,因为Flask-SQLAlchemy只接受一个连接字符串参数:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
class Config(object):
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db?check_same_thread=False'
db = SQLAlchemy()
def create_app():
app.config.from_object(Config)
app = Flask(__name__)
db.init_app(app)
...
默认情况下,
check_same_thread
为True
,只有创建的主题可能 使用连接。如果设置False
,则返回的连接可能是 跨多个线程共享。 使用多个线程时 相同的连接写操作应该由用户序列化 避免数据损坏。
答案 1 :(得分:16)
如果跨线程共享会话,则SQLAlchemy(在本例中也是SQLite)不起作用。您可能没有显式使用线程,但是mod_wsgi
是,并且您已经定义了一个全局session
对象。使用scoped_session
来处理为每个线程创建唯一会话。
session = scoped_session(sessionmaker(bind=engine))
@app.teardown_request
def remove_session(ex=None):
session.remove()
@app.route('/')
def example():
item = session.query(MyModel).filter(...).all()
...
最好使用Flask-SQLAlchemy为您处理此事和其他事情。 SQLAlchemy文档建议您使用集成库,而不是自己这样做。
db = SQLAlchemy(app)
@app.route('/')
def example():
item = db.session.query(MyModel).filter(...).all()
...
另请注意,您应该只定义引擎,会话等一次并将其导入其他位置,而不是像当前代码那样在每个文件中重新定义它。