我有一个python flask应用程序,可以从json请求接收数据,然后进行处理。
我的代码示例如下:-
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, request, url_for, copy_current_request_context
from time import sleep
from threading import Thread, Event
__author__ = 'shark'
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
# turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)
thread = Thread()
thread_stop_event = Event()
@app.route('/platform-data', methods=['POST'])
def platformData():
"""
Generate a random number every 1 second and emit to a socketio instance (broadcast)
Ideally to be run in a separate thread?
"""
# infinite loop of magical random numbers
print("Receiving platform data")
while not thread_stop_event.isSet():
req_data = request.get_json()
id = req_data['id']
latitude = req_data['coordinates'][1]
longitude = req_data['coordinates'][0]
speed = req_data['speed']
angle = req_data['angle']
length = req_data['dimensions'][0]
width = req_data['dimensions'][1]
laneW = req_data['lane_width']
spdLmt = req_data['speed_limit']
# return testProcess(speed)
# print(id, latitude, longitude, speed, angle, length, width, laneW, spdLmt)
def testProcess(id,speed):
if speed > 30:
print(id, " ", "slow down")
else:
print(id," ", "ok")
testProcess(id,speed)
# return {"speed": speed}
# socketio.emit('speed', {'speed': speed}, namespace='/test')
socketio.sleep(1)
@app.route('/')
def index():
# only by sending this page first will the client be connected to the socketio instance
return render_template('index.html')
@socketio.on('connect', namespace='/test')
def test_connect():
# need visibility of the global thread object
global thread
print('Client connected')
# Start the random number generator thread only if the thread has not been started before.
if not thread.isAlive():
print("Starting Thread")
thread = socketio.start_background_task(platformData)
@socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app)
我需要创建该应用的方式是,它会根据每个请求的ID为实时收到的请求创建一个单独的线程。具有相同ID的请求将被定向到运行该特定ID的线程。
我的json请求如下:-
{
"id" : "1"
"speed" : 20
}
我想为testProcess()
中的每个唯一ID创建一个唯一线程,并根据该ID的速度提供输出。当前,当我为相同的id传递两种不同的速度时,将创建2个单独的线程。但是我需要在为每个唯一ID唯一创建的同一线程中更新更改。
有关如何执行此操作的任何想法?
我真的没收到你的问题。应该穿线哪一部分?
您可以在Python中使用内置的threading
类。
from threading import Thread
def task_that_should_run_threaded():
pass
task = Thread(target=task_that_should_run_threaded)
如果您要运行此任务,只需执行:
task.run()
当您想等待响应时使用join()
[请再次为我解释您的问题,我将调整答案。