我正在尝试使用 Python Flask 流式传输来自 SocketIO 的响应。
我遇到一个错误: TypeError: 'NoneType' 对象不可调用 视图函数未返回有效响应。返回类型必须是字符串、字典、列表、带有标题或状态的元组、响应实例或可调用的 WSGI,但它是一个函数。
app = Flask(__name__)
socketio = SocketIO(app)
@app.route("/test", methods=["POST"])
def test():
def stream(socketio):
print('stream function executed')
dummy_response = "This is a dummy response." # Replace with your desired dummy response
for _ in range(5): # Send the dummy response 5 times
socketio.emit('answer', {'answer': dummy_response})
threading.Thread(target=stream, args=(socketio)).start()
return jsonify({"message": "Question received"})
if __name__ == "__main__":
socketio.run(app, port=3000)
打开套接字的单独脚本是:
import subprocess
import socketio
sio = socketio.Client()
@sio.on('connect')
def on_connect():
print('Connected to the WebSocket server')
@sio.on('stream_response')
def handle_stream_response(data):
print('Received response:', data)
sio.connect('http://localhost:3000')
sio.wait()
# Send POST request to the endpoint using curl
subprocess.Popen(['curl', '--http1.1', '-X', 'POST',
'-F,'http://localhost:3000/test'])
所以现在我只想传递虚拟字符串来修复错误,然后我将实现真正的功能。
现在我只想启用流式响应。