我阅读了很多有关问题的解决方案,然后找到了一个。但这仅是针对单个URL路由定义的。现在,如果我想对两个URL执行相同的操作,则无法执行。
这是适用于单个URL的解决方案,但我想为2个URL返回2个不同的响应,而是为两个URL返回相同的响应。
import traceback
import flask
import time
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
app = flask.Flask("after_response")
AfterResponse(app)
@app.after_response
def after_deal():
time.sleep(10)
print("Done")
@app.route("/hello/<id>")
def hello(id):
return "Hello world!"
@app.route("/fun")
def fun():
return "Hello Fun"
if __name__ == '__main__':
app.run(debug=True)
现在我想要的是,当我调用“ hello / id” URL时,after_response应该返回“ Done”,但是当我调用“ fun” URL时,after_response应该返回“ Fun Done”。这是不同的从您向我建议的解决方案中获取。因为您的解决方案尚未完成。 我将不胜感激。 谢谢