Python matraz que devuelve valores en tiempo real

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)

Noticias

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")

preguntado el 25 de septiembre de 13 a las 11:09

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 -

@ThiefMaster : exactly thats what I tried now. Please see my update -

1 Respuestas

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.

Respondido el 25 de Septiembre de 13 a las 13:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.