python – 使用flask的socketio扩展从线程发出
作者:互联网
我想向套接字客户端发出延迟消息.例如,当新客户端连接时,应该向客户端发出“正在检查”消息,并且在一定时间之后应该发出来自线程的另一个消息.
@socket.on('doSomething', namespace='/test')
def onDoSomething(data):
t = threading.Timer(4, checkSomeResources)
t.start()
emit('doingSomething', 'checking is started')
def checkSomeResources()
# ...
# some work which takes several seconds comes here
# ...
emit('doingSomething', 'checking is done')
但由于上下文问题,代码不起作用.我明白了
RuntimeError('working outside of request context')
是否有可能从线程发出?
解决方法:
问题是线程没有上下文来知道要将消息发送到哪个用户.
您可以将request.namespace作为参数传递给线程,然后使用它发送消息.例:
@socket.on('doSomething', namespace='/test')
def onDoSomething(data):
t = threading.Timer(4, checkSomeResources, request.namespace)
t.start()
emit('doingSomething', 'checking is started')
def checkSomeResources(namespace)
# ...
# some work which takes several seconds comes here
# ...
namespace.emit('doingSomething', 'checking is done')
标签:python,multithreading,socket-io,flask,flask-socketio 来源: https://codeday.me/bug/20190624/1276027.html