简体   繁体   中英

How to return 202 Accepted in Flask?

I had trying to make a Flask application. I want make some file like this:

# ...
@app.route("/search") # Because Lynx can't play JavaScript
def search():
    # Return an 202 Accepted
    # Very long times searching...
    # Return result
# ...

So how can I let it return a 202 Accepted but don't return from the function?

from threading import Thread

@app.route("/search"):
def search():
    def my_thread():
        # Search
        # Store the result somewhere so that a separate request
        # can be done to get result
    thread = Thread(target=my_thread)
    thread.start()
    return "Long request", 202

You might want to use something like Celery, it's built for doing asynchronous tasks

return a 202 Accepted but don't return from the function

This is impossible, as python docs put it

return leaves the current function call with the expression list (or None ) as return value.

So return does terminates function, this does hold for python as whole (is not limited to flask )

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