1

I read a lot of solutions regarding my problem and I found one. But that was defined only for a single URL route . Now , if I want to execute the same thing for two URLs , I am not able to do it .

This is the solution that is working for the single url but I want to return 2 different responses for 2 URLs and instead it is returning the same response for both the URLs.

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)

Now what I want is that , when I call the "hello/id" URL, the after_response should return "Done" but when I call the "fun" URL, the after_response should return "Fun Done".It is different from the solution that you suggested to me.As it is not being done by your solution.
I would appreciate any kind of help. Thanks

jack
  • 101
  • 1
  • 9
  • Possible duplicate of [flask: \`@after\_this\_request\` not working](https://stackoverflow.com/questions/38993146/flask-after-this-request-not-working) – IonicSolutions Jun 07 '19 at 11:33

0 Answers0