简体   繁体   中英

Python-flask: How to redirect and then do task?

Suppose you these functions where a is some function that takes a while to do.

def a():
    sleep(5)
    return True
@app.route('/')
def b():
    a()
    return flask.redirect("http://someurl.com")

How would you get the same functionality but redirect first, then do the function? I'm using Heroku, and I don't want to have to completely restructure my code if I can help it.

Once you return a method (redirect in this case) it just dies, it can't keep running any code.

The only possible way to do this is to run the long task asynchronously. A very popular framework often used for this purpose is Celery. Check out their tutorial here . Here's a super quick introduction for using it with flask.

Note that you will need to run a separate service called a message broker for celery tu run. You can find details on it on the tutorial previously linked, but a quick solution and recommendation I can give from personal experience is to setup a Redis server with default configuration and it will just work.

Once you have everything running, you will first define your task with something like this:

@celery.task()
def a():
    sleep(5)
    return True

And then you will trigger the task this way:

def b():
    a.delay()
    return flask.redirect("http://someurl.com")

Hope that helps get you started with Celery.

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