Python-flask: How to redirect and then do task?
<p>Suppose you these functions where a is some function that takes a while to do.</p>

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

<p>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.</p>

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

<p>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 <a href="http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html" rel="nofollow">tutorial here</a>. Here's a <a href="http://flask.pocoo.org/docs/0.11/patterns/celery/" rel="nofollow">super quick introduction</a> for using it with flask.</p>

<p>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.</p>

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

<pre><code>@celery.task()
def a():
    sleep(5)
    return True
</code></pre>

<p>And then you will trigger the task this way:</p>

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

<p>Hope that helps get you started with Celery.</p>

python asynchronous flask