我有一个带有websockets的flask应用程序,当一个人点击一个套接字开始线程时,我希望它运行一个线程,比如:
@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
您(我)必须包含
thread.daemon = True
以通知应用程序将其作为后台进程运行,我删除了broadcast=True,因为这无论如何都不是必需的。你知道吗相关问题 更多 >
编程相关推荐