2015-01-05 21 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