Я прочитал много решений относительно моей проблемы и нашел одно. Но это было определено только для одного URL-маршрута. Теперь, если я хочу выполнить одно и то же для двух URL, я не смогу это сделать.
Это решение, которое работает для одного URL, но я хочу вернуть 2 разных ответа для 2 URL, и вместо этого оно возвращает одинаковый ответ для обоих 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)
Теперь я хочу, чтобы при вызове URL-адреса «hello / id» after_response возвращал «Done», но когда я вызываю URL «fun», after_response должен возвращать «Fun Done». из решения, которое вы предложили мне. Как это не делается вашим решением.
Буду признателен за любую помощь.
Спасибо