如何在等待请求完成时 return Flask 重定向?

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

我有一个 Flask 应用程序,其视图功能设置如下 (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)

我希望long_processing_function_that_may_fail()不要延迟重定向到外部站点的服务,尤其是在无法完成的情况下。但必须运行。理想情况下,long_processing_function_that_may_fail() 将在重定向发送给用户后 运行。满足这些要求的最佳方式是什么?

您可以在单独的线程中完成

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)