1、Flask Response生成流式数据api
注意return与def generate():是同级的
from flask import Flask, Responseapp = Flask(__name__)@app.route('/stream')
def stream_data():def generate():for i in range(5):time.sleep(1)yield f"Data chunk {i}\0" # 在每个数据块后添加换行符return Response(generate(), mimetype='text/plain')if __name__ == '__main__':app.run(debug=True)
2、iter_lines,iter_content遍历区别
iter_lines()方法是按行读取服务器返回的数据流。它会在遇到换行符或指定的分隔符(delimiter=b"\0")时,将数据流分割成多个块
iter_content()方法会在每次读取到指定大小的数据块时就返回该数据块,而不需要等待换行符或特定分隔符
1)iter_lines
服务端:
@app.route('/stream')
def stream_data():def generate():for i in range(5):time.sleep(1)yield f"Data chunk {i}\0" # 在每个数据块后添加换行符return Response(generate(), mimetype='text/plain')
客服端:
import requestsurl = 'http://localhost:5000/stream'
response = requests.get(url, stream=True)for line in response.iter_lines(chunk_size=1024, decode_unicode=False,delimiter=b"\0"):if line:print(line.decode('utf-8'), end='', flush=True) ##流式打印
2)iter_content
服务端:
@app.route('/stream')
def stream_data():def generate():for i in range(5):time.sleep(1)yield f"Data chunk {i}"
客户端:
import requestsurl = 'http://localhost:5000/stream'
response = requests.get(url, stream=True)for chunk in response.iter_content(chunk_size=10, decode_unicode=True):if chunk:print(chunk, end='', flush=True)