恕我直言,线程在这里也使事情变得不必要的复杂化。要在不引入线程的情况下完成您想要做的事情,您可以挂接到WSGI响应关闭方法 https://www.python.org/dev/peps/pep-0333/#specification-details。最简单的方法是使用 werkzeug关闭迭代器 http://werkzeug.pocoo.org/docs/0.14/wsgi/#werkzeug.wsgi.ClosingIterator helper.
import traceback
from werkzeug.wsgi import ClosingIterator
class AfterThisResponse:
def __init__(self, app=None):
self.callbacks = []
if app:
self.init_app(app)
def __call__(self, callback):
self.callbacks.append(callback)
return callback
def init_app(self, app):
# install extensioe
app.after_this_response = self
# install middleware
app.wsgi_app = AfterThisResponseMiddleware(app.wsgi_app, self)
def flush(self):
try:
for fn in self.callbacks:
try:
fn()
except Exception:
traceback.print_exc()
finally:
self.callbacks = []
class AfterThisResponseMiddleware:
def __init__(self, application, after_this_response_ext):
self.application = application
self.after_this_response_ext = after_this_response_ext
def __call__(self, environ, start_response):
iterator = self.application(environ, start_response)
try:
return ClosingIterator(iterator, [self.after_this_response_ext.flush])
except Exception:
traceback.print_exc()
return iterator
然后您可以像这样使用这个扩展:
import flask
import time
app = flask.Flask("after_response")
AfterThisResponse(app)
@app.route("/")
def home():
@app.after_this_response
def post_process():
time.sleep(2)
print("after_response")
return "Success!\n"
当您卷曲时,您将立即看到成功,然后 2 秒后在日志中您将看到“after_response”消息:
127.0.0.1 - - [25/Jun/2018 16:15:01] "GET / HTTP/1.1" 200 -
after_response
该解决方案是根据我的答案改编的摘要:
- Flask 中返回响应后需要执行一个函数 https://stackoverflow.com/questions/18082683/need-to-execute-a-function-after-returning-the-response-in-flask/51027637#51027637
- Flask结束响应并继续处理 https://stackoverflow.com/questions/17293311/flask-end-response-and-continue-processing/51027454#51027454
- Flask 返回响应后执行函数 https://stackoverflow.com/questions/48994440/execute-a-function-after-flask-returns-response/51013358#51013358