Flask——基于python完整实现客户端和服务器后端流式哀求及响应 ...

打印 上一主题 下一主题

主题 527|帖子 527|积分 1581

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



  • requests.post得到流式复兴的紧张参数:

    • stream:需要设置为True;
    • response.iter_content:使用该函数接收返回的流式数据。

  1. import requests
  2. import time
  3. import json
  4. def generate_stream_data():
  5.     # 假设这是要发送的文本列表
  6.     is_end = False
  7.     lines = ["Hello", "world", "this", "is", "a", "stream", "of", "text"]
  8.     for line in lines:
  9.         print(line)
  10.         if lines.index(line) == len(lines) - 1:
  11.             is_end = True
  12.         yield json.dumps({'line': line, 'is_end': is_end}) + '\n'
  13.         time.sleep(0.5)
  14.         # 模拟数据处理时间
  15. def get_stream_response(response):
  16.     # 流式接收response
  17.     rec_data_list = []
  18.     temp_data = ''
  19.     for chunk in response.iter_content(chunk_size=1):
  20.         temp_data += chunk.decode('utf-8')
  21.         if temp_data.endswith('\n'):
  22.             temp_json = json.loads(temp_data)
  23.             rec_data_list.append(temp_json)
  24.             print(temp_data)
  25.             temp_data = ''
  26.             if temp_json['is_end']:
  27.                 break
  28.     print(rec_data_list)
  29.     print("----------------------------")
  30.     print(temp_data)
  31.     return rec_data_list
  32. def stream_upload(url):
  33.    
  34.     # 流式接收response
  35.     response = requests.post(url, data=generate_stream_data(), stream=True)
  36.    
  37.     final_response = get_stream_response(response)
  38.    
  39.     return final_response
  40. url = 'http://127.0.0.1:5000/stream'
  41. response = stream_upload(url)
复制代码
Flask服务器后端



  • flask.request流式获取数据::

    • 使用request.stream.read读取数据,而不是get_data()等一次性函数。

  1. from flask import Flask, Response, request
  2. import time
  3. import json
  4. import requests
  5. app = Flask(__name__)
  6. def process_stream_data(stream_data):
  7.     # 假设这是要发送的数据
  8.     print("开始生成新的数据流")
  9.     is_end = False
  10.     print(stream_data)
  11.     for idx, line in enumerate(stream_data):
  12.         if idx == len(stream_data)-1:
  13.             is_end = True
  14.         print(line)
  15.         yield json.dumps(line)+"\n"
  16.         time.sleep(0.5)
  17.         # 模拟数据处理时间
  18. def get_stream_request(chunk_size=1):
  19.     req_data_list = []
  20.     temp_data = ''
  21.     while True:
  22.         chunk = request.stream.read(chunk_size)
  23.         temp_data += chunk.decode('utf-8')
  24.         if temp_data.endswith('\n'):
  25.             temp_json = json.loads(temp_data)
  26.             req_data_list.append(temp_json)
  27.             print(temp_data)
  28.             temp_data = ''
  29.             if temp_json['is_end']:
  30.                 return req_data_list
  31. @app.route('/stream', methods=['POST'])
  32. def stream_text():
  33.    
  34.     data = get_stream_request()
  35.     print("----------------------------")
  36.    
  37.     return Response(process_stream_data(data))
  38. if __name__ == "__main__":
  39.     app.run(host='0.0.0.0', port=5000, debug=True)
复制代码
客户端/服务器端流式接收[打字机]结果



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

缠丝猫

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表