执行以下代码时会出现以下错误

时间:2014-12-30 08:45:19

标签: python multithreading flask socket.io mongoengine

执行以下代码时,错误执行超出上下文。 我不知道怎么解决它请帮帮我。 我正在使用烧瓶mongoengine和线程概念。

我认为烧瓶中的上下文概念可能对我有用,但我没有得到任何解决方案。

@app.route('/home')
def home():
    users_list = []


    global thread
    if thread is None:
        thread = Thread(target=check_messages_came)
        thread.start()

    if session['username'] != '':
        data = users.objects(username__ne=session['username'])
        for user in data:
            users_list.append(user.username)
        #s_data = json.dumps(data, cls=MongoengineObjectsJsonEncoder)
        return render_template('home.html',data=(users_list),me = session['username'])

     else:
        return redirect(url_for('login'))

上面的函数是加载主页并调用线程。线程代码如下所示。

def check_messages_came():
    """Example of how to send server generated events to clients."""
    count = 0 
    while True:
        print 'thread running'
        data =  messages.objects( Q(user2=session['username']) & Q(transfered_data=False))
        if data:
            socketio.emit('my response',{'data': 'some messages are got', 'count': count},
                      namespace='/test')
        else:
            socketio.emit('my response',{'data': 'no message to read', 'count': count},
                      namespace='/test')

        count += 1
        time.sleep(2)

删除data = messages.objects()正常运行,但如果存在则会产生以下错误

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "app.py", line 31, in check_messages_came
data =  messages.objects( Q(user2=session['username']) & Q(transfered_data=False))
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 368, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
 File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 297, in    _get_current_object
return self.__local()
 File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context

0 个答案:

没有答案