python实现stream流式传输,边生成,边返回给客户端

服务器代码

import threading
import time
from typing import Generator

from flask import Flask, Response, stream_with_context

app = Flask(__name__)
arr = []

def append_item(num):
while True:
num += 1
print("append_item", num)
arr.append(num)
time.sleep(1)


def generate_arr(g_arr) -> Generator:
while True:
for i in g_arr:
print(str(i))
yield str(i)
time.sleep(2)

@app.route('/stream', methods=['GET'])
def stream():

# 这里要再开一个线程,才不会阻塞主进程传输数据
append_item_thread = threading.Thread(target=append_item, kwargs={"num": 0})
append_item_thread.start()
return Response(stream_with_context(generate_arr(arr)),content_type='application/octet-stream')

if __name__ == "__main__":
app.run(port=5005)

客户端请求代码 

import requests

url = 'http://localhost:5005/stream'

response = requests.get(url, stream=True)
# chunk_size每次返回块的大小
for chunk in response.iter_content(chunk_size=5):
if chunk:
print(chunk.decode())

你可能感兴趣的:(python,flask,开发语言)