使用 Flask 的 socketio 扩展从线程发射

Mua*_*tik 5 python multithreading flask socket.io 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')
Run Code Online (Sandbox Code Playgroud)

但是由于上下文问题,代码不起作用。我得到

RuntimeError('working outside of request context')
Run Code Online (Sandbox Code Playgroud)

是否可以从线程发出?

Mig*_*uel 4

问题在于线程没有上下文来知道要将消息发送给哪个用户。

您可以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')
Run Code Online (Sandbox Code Playgroud)