简体   繁体   中英

Flask not streaming JSON response

I have below flask application that should stream JSON response

Directory structure:

server - 
        api.py
        resources -
                   stream.py

api.py

from flask import Flask
from flask_restful import Api
from resources.stream import Stream
from flask_compress import Compress

compress = Compress()
app = Flask(__name__)
compress.init_app(app)
api = Api(app)
api.add_resource(Stream, '/stream')
if __name__ == '__main__':
    app.run(debug=False,host='0.0.0.0')

stream.py in resources directory

from flask import Response, request, stream_with_context
from flask_restful import Resource

class Stream(Resource):
    def get(self):
        def generator():
            yield '{"data": ['
            #creating large number of entries for data array with yield
            yield ']}'
        resp = Response(stream_with_context(generator()), status=200, content_type='application/json')
        return resp     

I started the flask app with python3.9 api.py

I am able to get response when I hit url http://127.0.0.1:5000/stream but in network tab I can see some issues:

  1. If the response was streamed it should not have content-length
  2. The streamed response should not be in Waiting for server response state, somehow its waiting to finish whole response and then starts downloading.

内容长度 我得到的输出

And below is the output that I am trying to achieve. A streamed output which would start Content Downloading and not be stuck in Waiting for server response 预期的

I found the solution for the problem I faced. I was using flask_compress which was causing this issue. Removing it would stream the response as expected. Thank you for the help though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM