Flask——基于python完整实现客户端和服务器后端流式请求及响应
创始人
2025-01-20 15:35:55
0

文章目录

    • 本地客户端
    • Flask服务器后端
    • 客户端/服务器端流式接收[打字机]效果

看了很多相关博客,但是都没有本地客户端和服务器后端的完整代码示例,有的也只说了如何流式获取后端结果,基本没有讲两端如何同时实现流式输入输出,特此整理总结,给大家交流学习和使用!

本地客户端

  • requests.post得到流式回复的重要参数:
    • stream:需要设置为True;
    • response.iter_content:使用该函数接收返回的流式数据。
import requests import time import json  def generate_stream_data():     # 假设这是要发送的文本列表     is_end = False     lines = ["Hello", "world", "this", "is", "a", "stream", "of", "text"]     for line in lines:         print(line)         if lines.index(line) == len(lines) - 1:             is_end = True         yield json.dumps({'line': line, 'is_end': is_end}) + '\n'         time.sleep(0.5)         # 模拟数据处理时间  def get_stream_response(response):     # 流式接收response     rec_data_list = []     temp_data = ''     for chunk in response.iter_content(chunk_size=1):         temp_data += chunk.decode('utf-8')         if temp_data.endswith('\n'):             temp_json = json.loads(temp_data)             rec_data_list.append(temp_json)             print(temp_data)             temp_data = ''             if temp_json['is_end']:                 break     print(rec_data_list)     print("----------------------------")     print(temp_data)     return rec_data_list  def stream_upload(url):          # 流式接收response     response = requests.post(url, data=generate_stream_data(), stream=True)          final_response = get_stream_response(response)          return final_response  url = 'http://127.0.0.1:5000/stream' response = stream_upload(url) 

Flask服务器后端

  • flask.request流式获取数据::
    • 使用request.stream.read读取数据,而不是get_data()等一次性函数。
from flask import Flask, Response, request import time import json import requests  app = Flask(__name__)  def process_stream_data(stream_data):     # 假设这是要发送的数据     print("开始生成新的数据流")     is_end = False     print(stream_data)     for idx, line in enumerate(stream_data):         if idx == len(stream_data)-1:             is_end = True         print(line)         yield json.dumps(line)+"\n"         time.sleep(0.5)         # 模拟数据处理时间  def get_stream_request(chunk_size=1):     req_data_list = []     temp_data = ''     while True:         chunk = request.stream.read(chunk_size)         temp_data += chunk.decode('utf-8')         if temp_data.endswith('\n'):             temp_json = json.loads(temp_data)             req_data_list.append(temp_json)             print(temp_data)             temp_data = ''             if temp_json['is_end']:                 return req_data_list  @app.route('/stream', methods=['POST']) def stream_text():          data = get_stream_request()      print("----------------------------")          return Response(process_stream_data(data))  if __name__ == "__main__":     app.run(host='0.0.0.0', port=5000, debug=True) 

客户端/服务器端流式接收[打字机]效果

请添加图片描述

相关内容

热门资讯

现有说明如下!旺旺填大坑透视挂... 现有说明如下!旺旺填大坑透视挂(辅助)竟然是真的辅助软件(有挂方式)-哔哩哔哩1、这是跨平台的旺旺填...
总结透视!wepokerplu... 总结透视!wepokerplus外开挂,hh poker软件,策略教程(有挂技术)-哔哩哔哩1、金币...
重大通报!!都莱大菠萝辅助器,... 重大通报!!都莱大菠萝辅助器,德州局hhpoker,攻略教程(有挂解密)-哔哩哔哩1)都莱大菠萝辅助...
据统计!微玩盒子网页游戏辅助(... 据统计!微玩盒子网页游戏辅助(辅助)总是是有辅助下载(有挂细节)-哔哩哔哩1、微玩盒子网页游戏辅助有...
必备透视!wepoker免费脚... 必备透视!wepoker免费脚本咨询,wepokerplus辅助,指南教程(有挂教程)-哔哩哔哩必备...
分享给玩家!中至赣牌圈有没有辅... 分享给玩家!中至赣牌圈有没有辅助,wepoker免费脚本弱密码,绝活儿教程(有挂教学)-哔哩哔哩1、...
普及透视!hhpoker有后台... 普及透视!hhpoker有后台操作吗,aapoker能控制牌吗,讲义教程(有挂技巧)-哔哩哔哩亲,关...
此事引发网友热议!心悦辅助器(... 此事引发网友热议!心悦辅助器(辅助)总是存在有辅助插件(有挂透视)-哔哩哔哩此事引发网友热议!心悦辅...
重大通报!!广丰510k辅助,... 重大通报!!广丰510k辅助,德州透视hhpoker,策略教程(有挂猫腻)-哔哩哔哩1)广丰510k...
辅助透视!哈糖大菠萝开挂,hh... 辅助透视!哈糖大菠萝开挂,hhpoker为什么一直输,手段教程(有挂规律)-哔哩哔哩1、全新机制【h...