我一直在使用、Python和库开发一个应用程序。我遇到的问题是,由于某些上下文问题,下面的代码不能正确地执行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中,我一直在阅读一些解决方案,但它们没有奏效。我不知道我做错了什么。
我尝试在我的with app.app_context():之前添加一个emit
def someotherfunction():
# some other tasks
with app.app_context():
emit('anEvent', jsondata, namespace='/test') # same error here我尝试过的另一个解决方案是在copy_current_request_context之前添加装饰器someotherfunction(),但是它说装饰器必须在本地范围内。我把它放在someotherfunction()中,第一行,但是同样的错误。
如果有人能帮我做这件事我会很高兴的。提前谢谢。
发布于 2015-07-27 11:21:42
您的错误是“在请求上下文之外工作”。您试图通过推送应用程序上下文来解决这个问题。相反,您应该推送请求上下文。参见http://kronosapiens.github.io/blog/2014/08/14/understanding-contexts-in-flask.html上的烧瓶对上下文的解释
您的函数()中的代码可能使用请求上下文中的全局对象(如果我不得不猜测您可能使用请求对象)。您的代码可能在新线程中未执行时工作。但是,当您在一个新线程中执行它时,您的函数不再在原始请求上下文中执行,并且它不再具有对请求上下文特定对象的访问权限。所以你得手动推它。
所以你的职能应该是
def someotherfunction():
with app.test_request_context('/'):
emit('anEvent', jsondata, namespace='/test')发布于 2017-03-28 21:02:24
您在这里使用了错误的emit。您必须使用您创建的socketio对象的发出。因此,不是
emit('anEvent', jsondata, namespace='/test') # here occurs the error使用:socketio.emit('anEvent', jsondata, namespace='/test') # here occurs the error
https://stackoverflow.com/questions/31647081
复制相似问题