在python流式处理请求中,在请求完成执行循环之前不接收响应
我正在尝试用python实现流式处理。我需要将巨大的结果从游标返回到RESTAPI。我在返回响应时将flask stream_与_上下文一起使用。但当我尝试使用stream=True标志进行请求时,我的请求将等待响应,直到游标执行所有数据 期望收到1至10个元素时,一个接一个得到收益的响应。但是test.py中的请求者会等待,直到所有元素都从service_runner.py处理完毕在python流式处理请求中,在请求完成执行循环之前不接收响应,python,json,rest,response,Python,Json,Rest,Response,我正在尝试用python实现流式处理。我需要将巨大的结果从游标返回到RESTAPI。我在返回响应时将flask stream_与_上下文一起使用。但当我尝试使用stream=True标志进行请求时,我的请求将等待响应,直到游标执行所有数据 期望收到1至10个元素时,一个接一个得到收益的响应。但是test.py中的请求者会等待,直到所有元素都从service_runner.py处理完毕 from flask import Flask, stream_with_context, Response i
from flask import Flask, stream_with_context, Response
import time, json
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/StreamData')
def StreamData():
def stream1():
for i in range(10):
print(i)
time.sleep(1) # this is to see requestor recives stream or not.
yield json.dumps(i)
return Response(stream_with_context(stream1()))
下面是代码示例。
服务_runner.py
from flask import Flask, stream_with_context, Response
import time, json
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/StreamData')
def StreamData():
def stream1():
for i in range(10):
print(i)
time.sleep(1) # this is to see requestor recives stream or not.
yield json.dumps(i)
return Response(stream_with_context(stream1()))
test.py
import requests, asyncio, aiohttp
URL='http://127.0.0.1:5000/StreamData'
def TestStream():
req1 = requests.get(URL, stream=True)
print(req1)
for r in req1.iter_lines(chunk_size=1):
print(r)
async def TestWithAsync():
async with aiohttp.ClientSession() as session:
async with session.get(URL) as resp:
print(await resp.content.read())
def main():
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(TestWithAsync())
event_loop.close()
if __name__=='__main__':
TestStream()
main()