烧瓶。应用程序上下文和访问db.session的新线程。应用程序未在db实例上注册,也没有应用程序绑定到当前上下文

时间:2014-05-23 07:55:58

标签: python multithreading flask sqlalchemy

我在Flask + sqlalchemy上有一个应用程序。 我需要延迟从数据库中删除对象。 为此,我写了一个带定时器的课程。

from threading import Timer
from ..extensions import db
# db = SQLAlchemy()

class Remover(object):
    """docstring for Remover"""
    def __init__(self, obj):
        super(Remover, self).__init__()
        self.obj = obj
        self.t = Timer(10, self.remove)
        self.t.start()

    def remove(self):
        try:
            db.session.delete(self.obj)
            db.session.commit()
        except Exception, e:
            raise e

    def cancel(self):
        self.t.cancel()

u = User().query.first()
Remover(u)

但计时器是在一个新线程中启动的。也许这就是我得到例外的原因:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 808, in __bootstrap_inner
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 1080, in run
    self.function(*self.args, **self.kwargs)
  File "/Users/egregors/pythonProject/RSys/rSystem/admin/views.py", line 638, in remove
    raise e
RuntimeError: application not registered on db instance and no
application bound to current context

有没有人知道你是如何正确实现这样一个类的? 如何使用线程和应用程序上下文?

由于

1 个答案:

答案 0 :(得分:2)

请阅读http://flask.pocoo.org/docs/0.10/appcontext/,然后尝试:

with app.app_context():
    db.session.delete(self.obj)
    db.session.commit()