Search code examples
pythonweb-servicesflaskpartial

is there a way to partially return results from Python web service....?


I am new to python. I am using Flask for creating a web service which makes lots of api calls to linkedin. The problem with this is getting the final result set lot of time and frontend remains idle for this time. I was thinking of returning partial results found till that point and continuing api calling at server side. Is there any way to do it in Python? Thanks.


Solution

  • Flask has the ability to stream data back to the client. Sometimes this requires javascript modifications to do what you want but it is possible to send content to a user in chunks using flask and jinja2. It requires some wrangling but it's doable.

    A view that uses a generator to break up content could look like this (though the linked to SO answer is much more comprehensive).

    from flask import Response
    
    @app.route('/image')
    def generate_large_image():
        def generate():
            while True:
                if not processing_finished():
                    yield ""
                else:
                    yield get_image()
        return Response(generate(), mimetype='image/jpeg')