2024-05-20 22:41:31 发布
网友
对于一个单独的请求,我需要在向客户端发送响应之后执行一个函数。因为这个函数需要时间,最后会出现连接超时Socket error: [Errno 32] Broken pipe
Socket error: [Errno 32] Broken pipe
返回请求后,Flask中是否有执行函数的方法
比flask迭代器解决方案更通用的解决方案是编写一个WSGI中间件,该中间件向response close方法添加回调。在这里,我们使用werkzeugClosingIterator帮助程序和flask应用程序扩展来实现这一点:
import traceback from werkzeug.wsgi import ClosingIterator class AfterResponse: 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 extension app.after_response = self # install middleware app.wsgi_app = AfterResponseMiddleware(app.wsgi_app, self) def flush(self): for fn in self.callbacks: try: fn() except Exception: traceback.print_exc() class AfterResponseMiddleware: def __init__(self, application, after_response_ext): self.application = application self.after_response_ext = after_response_ext def __call__(self, environ, after_response): iterator = self.application(environ, after_response) try: return ClosingIterator(iterator, [self.after_response_ext.flush]) except Exception: traceback.print_exc() return iterator
然后,您可以像这样使用after_response装饰器:
after_response
import flask import time app = flask.Flask("after_response") AfterResponse(app) @app.after_response def after(): time.sleep(2) print("after_response") @app.route("/") def home(): return "Success!\n"
当你卷曲它时,你会看到它立即响应并且卷曲关闭,然后2秒后你的“after”消息出现在日志中:
127.0.0.1 - - [25/Jun/2018 15:41:51] "GET / HTTP/1.1" 200 - after_response
这个答案是从我的答案here和here中总结出来的。
比flask迭代器解决方案更通用的解决方案是编写一个WSGI中间件,该中间件向response close方法添加回调。在这里,我们使用werkzeugClosingIterator帮助程序和flask应用程序扩展来实现这一点:
然后,您可以像这样使用
after_response
装饰器:当你卷曲它时,你会看到它立即响应并且卷曲关闭,然后2秒后你的“after”消息出现在日志中:
这个答案是从我的答案here和here中总结出来的。
相关问题 更多 >
编程相关推荐