python - 将从json请求接收到的数据传递给python flask socketio中的另一个函数
问题描述
我有一个从 json 接收数据的 python 烧瓶应用程序。我还使用了 socketio 和线程来实时处理数据。在我的程序中,我需要将从 json 请求接收到的数据发送到另一个 python 函数。以下是我为此编写的代码: -
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, request, url_for, copy_current_request_context
from random import random
from time import sleep
from pygeodesy.ellipsoidalVincenty import LatLon
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)
# random number Generator Thread
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)
def testProcess(speed):
if speed>30:
print("slow down")
socketio.emit('speed', {'speed': speed}, namespace='/test')
socketio.sleep(.5)
@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)
但是,当我从 Postman 运行应用程序和 POST 数据时,我在控制台中收到以下错误:-
TypeError:视图函数没有返回有效响应。返回类型必须是字符串、字典、元组、响应实例或可调用的 WSGI,但它是 int。127.0.0.1 - - [2020 年 3 月 5 日 17:06:25]“POST /平台数据 HTTP/1.1”500 15625 0.008975
我知道这样做的原因是我已经声明了return testProcess(speed)
.
因此,我需要知道将速度变量传递给“testProcess”函数的正确方法。
解决方案
platformData() 必须返回一个字符串、字典、元组、响应实例或 WSGI 可调用,但您返回未定义的 testProcess 的返回尝试:
def testProcess(speed):
if speed>30:
return "slow down"
else:
return "ok"
或者只是调用 testProcess(speed) 而不返回,然后返回其他东西
推荐阅读
- c# - 激活器创建通用实例
- sql - 当两个或多个条件为真时如何取反
- google-chrome - engine: 'chrome' 和 engine: 'chromy' 在 backstop.config 有什么区别?
- javascript - 如何从事务保存搜索/Suitescript 搜索中获取销售订单“shipaddresslist”值?
- javascript - 为什么我的循环只返回 HTML 集合中的第一个值
- opencl - OpenCL:clSetKernelArg 与 clSetKernelArg + clEnqueueWriteBuffer
- r - 在pdf输出中编织时如何在R Markdown中证明(两边)文本
- python - 告诉 LabelEnocder 忽略新标签?
- mysql - 通过 magmi 导入的产品不会自动保存
- r - 如何使用 write_tsv 保存的 tibble 可以被 read_tsv 读取