【发布时间】:2015-10-17 06:48:41
【问题描述】:
我一直在使用 Flask、Python 和 Flask-Socket.io 库开发应用程序。我遇到的问题是,由于某些上下文问题,以下代码无法正确执行emit
RuntimeError: working outside of request context
我现在只为整个程序编写一个 python 文件。这是我的代码(test.py):
from threading import Thread
from flask import Flask, render_template, session, request, jsonify, current_app, copy_current_request_context
from flask.ext.socketio import *
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
def somefunction():
# some tasks
someotherfunction()
def someotherfunction():
# some other tasks
emit('anEvent', jsondata, namespace='/test') # here occurs the error
@socketio.on('connect', namespace='/test')
def setupconnect():
global someThread
someThread = Thread(target=somefunction)
someThread.daemon = True
if __name__ == '__main__':
socketio.run(app)
在 StackExchange 中,我一直在阅读一些解决方案,但没有奏效。我不知道我做错了什么。
我尝试在emit 之前添加with app.app_context()::
def someotherfunction():
# some other tasks
with app.app_context():
emit('anEvent', jsondata, namespace='/test') # same error here
我尝试的另一个解决方案是在someotherfunction() 之前添加装饰器copy_current_request_context,但它说装饰器必须在本地范围内。我把它放在someotherfunction() 里面,第一行,但同样的错误。
如果有人可以帮助我,我会很高兴。提前致谢。
【问题讨论】:
-
我不是烧瓶专家,但我认为
setupconnect上的global someThread是问题的一部分。另外,也许这个帖子可以帮助你:stackoverflow.com/questions/9931738/…
标签: python multithreading sockets flask socket.io