【问题标题】:Threading a faker inside a flask app在烧瓶应用程序中插入伪造者
【发布时间】:2016-05-09 18:03:24
【问题描述】:

我有一个带有 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

【问题讨论】:

    标签: python multithreading python-2.7


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-18
      • 2015-09-07
      • 2016-12-23
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      相关资源
      最近更新 更多