Search code examples
pythonflaskpython-multithreading

How can I return a Flask redirect while wating for a request to complete?


I have a Flask app with a view function that is set up like this (MWE):

from flask import redirect
import time, random

def quick_processing_function():
    return True

def long_processing_function():
    time.sleep(15)
    return random.rand() < 0.99

@app.route('target')
def function():
    result = quick_processing_function()
    if result:
        long_processing_function_that_may_fail()
        return redirect(SOME_EXTERNAL_SITE)

I'd like long_processing_function_that_may_fail() to not delay the service of the redirect to the external site, especially if it fails to complete. But it must run. Ideally, long_processing_function_that_may_fail() would run after the redirect is sent to the user. What's the best way to meet these requirements?


Solution

  • You can do it in a separate thread

    from flask import redirect
    import threading
    import time, random
    
    def quick_processing_function():
        return True
    
    def long_processing_function():
        time.sleep(15)
        return random.rand() < 0.99
    
    @app.route('target')
    def function():
        result = quick_processing_function()
        if result:
            x = threading.Thread(target=long_processing_function_that_may_fail, args=())
            x.start()
            return redirect(SOME_EXTERNAL_SITE)