Skip to content
Advertisement

Is it possible to redirect inside a middleware class?

class Middleware:
    def __init__(self, app):
        self.app = app


    def __call__(self, environ, start_response):
        request = Request(environ)
        cookies = request.cookies
        path = request.path
        

        if not isAuthenticated(cookies):
            #Redirect to /login

        return self.app(environ, start_response)

So I have a Middleware class that is supposed to get the cookies from the request and then send it to a function isAuthenticated which returns either True or False now if the function returns False I need to redirect to /login page is that possible to do? even though I don’t have the request object I only have the environ?

Advertisement

Answer

Not sure. Because WSGI middleware is at a layer outside the app itself.

You can use other hooks to work inside app / request context. In this case you can use flask.request, flask.redirect() etc. By the way, you don’t need to initialize the request (request = Request (Environment)).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement