Andrew Melnikov
Andrew Melnikov

Reputation: 1

Return multiple times from one api call in Flask Restful

I want to call a generate() function and send a user a message, but then continue executing a function.

@application.route("/api/v1.0/gen", methods=['POST'])
def generate():
    return "Your id for getting the generated data is 'hgF8_dh4kdsRjdr'"
    main() #generate a data
    return "Successfully generated something. Use your id to get the data"

I understand that this is not a correct way of returning, but I hope you get the idea of what I am trying to accomplish. Maybe Flask has some build-in method to return multiple times from one api call?

Upvotes: 0

Views: 2202

Answers (1)

Alveona
Alveona

Reputation: 978

Basically, what are you describing is called Server-Sent Events (aka SSE)

The difference of this format, that they returned an 'eventstream' Response type instead of usual JSON/plaintext
And if you want to use it with python/flask, you need generators.

Small code example (with GET request):

@application.route("/api/v1.0/gen", methods=['GET'])
def stream():
    def eventStream():
        text = "Your id for getting the generated data is 'hgF8_dh4kdsRjdr'"
        yield str(Message(data = text, type="message"))
        main()
        text = "Successfully generated something. Use your id to get the data"
        yield str(Message(data = text, type="message"))
    resp.headers['Content-Type'] = 'text/event-stream'
    resp.headers['Cache-Control'] = 'no-cache'
    resp.headers['Connection'] = 'keep-alive'
    return resp

Message class you can find here: https://gist.github.com/Alveona/b79c6583561a1d8c260de7ba944757a7

And of course, you need specific client that can properly read such responses.
postwoman.io supports SSE at Real-Time tab

Upvotes: 1

Related Questions