2016-05-09 5 views
0

ich eine Flasche App mit WebSockets habe, und wenn eine Person eine Steckdose Einfädeln starten trifft, will ich es wie einen roten Faden laufen:Threading einen Fälscher in einem Kolben App

@socketio.on('start', namespace='/ws') 
def patrol(): 
    asset = {'x': 0, 'y': 1} 
    while True: 
     thread_patrol(asset, [[0, 0], [400, 400]]) 


def patrol(asset, coordinates): 
    count = 0 
    import itertools 
    for coordinate in itertools.cycle(coordinates): 
     val = True 
     while val: 
      asset, val = take_step(asset, coordinate[0], coordinate[1]) 
      emit('asset', 
       {'data': asset, 'count': count}, 
       broadcast=True) 
      count += 1 
      time.sleep(1) 


import threading 
def thread_patrol(asset, coordinates): 
    print('threading!') 
    patrolling_thread = threading.Thread(target=patrol, args=(asset, coordinates)) 
    patrolling_thread.start() 

def take_step(asset, x, y): 
    asset[x] = x 
    asset[y] = y 

Aber dann bekomme ich eine Fehler, weil es außerhalb des Anforderungskontextes liegt. Was muss ich tun, um meine Anwendung zu ermöglichen ?:

threading! 
Exception in thread Thread-2005: 
Traceback (most recent call last): 
    File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
    File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
    File "app2.py", line 270, in patrol 
    broadcast=True) 
    File "/usr/local/lib/python2.7/site-packages/flask_socketio/__init__.py", line 520, in emit 
    namespace = flask.request.namespace 
    File "/usr/local/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__ 
    return getattr(self._get_current_object(), name) 
    File "/usr/local/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object 
    return self.__local() 
    File "/usr/local/lib/python2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object 
    raise RuntimeError('working outside of request context') 
RuntimeError: working outside of request context 

Antwort

0

You (I) thread.daemon = True enthalten müssen einzufädeln die App zu informieren es als Hintergrundprozess zu laufen, und ich entfernt Broadcast = True seit dieser wasn Ist sowieso nicht nötig.

def thread_patrol(asset, coordinates): 
    patrolling_thread = Thread(target=patrol, args=(asset, coordinates)) 
    thread.daemon = True 
    thread.start()