0

I have created my micro web framework with flask which uses fabric to call the shell scripts which are in remote servers.

The shell script might take a longer time to get completed. I send the POST request from my browser and awaits for the results.

The fabric displays the real time contents on the flask run screen but flask returns the values to the browser after the completion of that remote script.

How can i make my flask to print that real time values on my browser screen ?

My flask piece:

@app.route("/abc/execute", methods=['POST'])
def execute_me():
    value = request.json['value']
    result = fabric_call(value)
    result = formations(result)
    return json.dumps(result)

My fabric piece:

def fabric_call(value):
    with settings(host_string='my server', user='user',password='passwd',warn_only=True):
        proc = run(my shell script)
        return json.dumps(proc)

Update

I tried streamin` as well. But it didn't work. The output is displayed to my curl POST after script's complete execution. What am I missing ?

@app.route("/abc/execute", methods=['POST'])
def execute_me():
    value = request.json['value']
    def generate():
        for row in formations(fabric_call(value)):
            yield row + '\n'
    return Response(generate(), mimetype="text/event-stream")
2
  • 1
    First of all, JSON and realtime do not mix. If you return JSON you can only return a complete object. What you could do of course is returning multiple JSON objects (e.e.g one per line). To do something like this in flask you need to return a response wrapping a generator that yields data whenever it's ready to be sent: flask.pocoo.org/docs/patterns/streaming Sep 25, 2013 at 12:16
  • @ThiefMaster : exactly thats what I tried now. Please see my update
    – Sathy
    Sep 25, 2013 at 12:20

1 Answer 1

0

First of all, you need to make sure your data source (formations()) is actually a generator that yields data when available. Right now it very much looks like it runs the command and only returns a value once it has completely finished.

Also, in case you are using AJAX to call your endpoint remember that you cannot use e.g. jQuery's $.ajax(); you need to use XHR directly and poll for new data instead of using the onreadystatechange event since you want data once it's available and not only when the request finished.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.