我有一个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传递两个不同的速度时,会创建两个独立的线程。但我需要在为每个唯一id唯一创建的同一线程中更新更改。
你知道怎么做吗?
我希望我现在答对了你的问题。你想要一个进程,有一个唯一的ID和一个可以更改的设置(速度(会运行吗?如果我错了,请纠正我。
然后我会使用Python的多处理工具。
在那里,你可以创建一个进程并启动它。多处理的优点是,你可以定义变量。这些变量可以在进程之间共享。然后,您必须小心同步访问,但这是多处理/线程的一个常见问题。
小示例:
from multiprocessing import Process, Value
import time
speed_var = Value('i', 0)
def testProcess(speed_var):
while True:
speed = speed_var.value
if speed >= 30:
print("It's running fast! Perfect")
else:
print("It's so slow, even my grandma would be faster")
print(speed)
time.sleep(0.05)
id_1 = Process(target=testProcess, args=(speed_var, ))
id_1.start()
speed = 0
while speed >= 40:
speed += 3
speed_var.value = speed
time.sleep(0.2)
id_1.terminate()
另一种方法是使用队列,而不是使用Values。然后,您可以等待队列中的元素并开始处理它。有关更多信息,请询问或阅读文档:https://docs.python.org/2/library/multiprocessing.html#shared-ctypes对象
如果你想用自己的Id运行多个进程,我会在自己的编写类中管理它。在那里,您可以将ID链接到进程,并管理其运行状态以及ID和描述。