2015-01-05 25 views
4

我想发送延迟的消息到套接字客户端。例如,当一个新的客户端连接时,“检查​​已经开始”消息应该发送给客户端,并且在一段时间之后应该发送来自线程的另一个消息。使用瓶子的插槽扩展从线程发射

@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') 

是否有可能使线程发光?

回答

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') 
+0

我想这个答案仍然会失败,如果你有长时间运行的线程。请参阅下面的答案。 –

+0

这确实对我没有帮助。 request.namespace是一个没有发射方法的字符串。我试过socketio.emit('doingSomething',namespace = request.namespace),但是这不适用于基于类的命名空间。仍然卡住! –

+0

注意此答案的日期。这适用于非常旧的版本。有关更新的示例,请参阅GitHub上Flask-SocketIO存储库上的示例应用程序。 – Miguel