7

Reading this page http://flask.pocoo.org/docs/patterns/streaming/ 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:

@app.route('/')
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?

1
  • BTW the output = somemethod(var1,var2,var3) sends output to the flask log, so there is output, I just want it to send it to the browser and the log. Commented Dec 18, 2012 at 21:59

1 Answer 1

12

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:

@app.route('/')
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')
Sign up to request clarification or add additional context in comments.

6 Comments

@Brian Just two notes: a) Ideally you want somemethod to return a generator itself (lazy evaluation). b) It's easier to stream newline delimited formats like CSV than JSON.
So I actually tried that but it waited for the method to complete and then promoted me to download the csv file. I rather have it display the output on the screen line by line, is that possible? Maybe I am misunderstanding the idea here..
@BrianCarpio - simply remove the mimetype argument (or change it to text/html)
I think my problem is that somemethod(var1,var2,var3) doesn't return until it's complete. I did change it to text/plan, but like you said I need somemethod to return a generator itself. Thanks.
@miku I realize it's only 10 years ago ;-) but why is CSV easier to stream than JSON? JSON is just text where periodic \n occurrences can easily be enforced. Or are there other considerations?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.