简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM