在烧瓶应用程序内穿过一个骗子

时间:2016-05-09 18:03:24

标签: python multithreading python-2.7

我有一个带有websockets的烧瓶应用程序,当一个人点击套接字开始线程时,我希望它运行一个如下的线程:

@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

但后来我收到错误,因为它不在请求上下文中。我需要做什么才能允许我的应用程序进行线程化?:

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

1 个答案:

答案 0 :(得分:0)

您(我)必须包含thread.daemon = True以通知应用将其作为后台进程运行,并且我删除了broadcast = True,因为无论如何都不需要。

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