Brian Carpio Brian Carpio - 1 year ago 173
Python Question

Flask Stream Output Of Function To Browser

Reading this page it seems like I might be able to do what I want, I have a simple url route that sends the output to json but I rather is stream the output:

def aws_api_route_puppet_apply(ip=None):
output = somemethod(var1,var2,var3)
return Response(json.dumps(output), mimetype='application/json')

Is there a way to stream the somemethod to the browser using just flask and HTML or do I need to use javascript?

Answer Source

Just like the documentation says, simply create a generator and yield each line you want to return to the client.

If output is 10 lines long, then the following will print each of the ten lines (as they're available) to the client:

def aws_api_route_puppet_apply(ip=None):
    def generate():
        for row in somemethod(var1,var2,var3):
            yield row + '\n'
    return Response(generate(),  mimetype='application/json')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download