1
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?

Kadiem Alqazzaz
  • 554
  • 1
  • 7
  • 22

2 Answers2

2

Its possible using HTTP 301 redirection:

class PrefixMiddleware(object):

    def __init__(self, app, prefix=''):
        self.app = app
        self.prefix = prefix

    def __call__(self, environ, start_response):
        if environ['PATH_INFO'].startswith(self.prefix):
            environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):]
            environ['SCRIPT_NAME'] = self.prefix
            return self.app(environ, start_response)
        else:
            start_response('301', [('Location', self.prefix)])
            return ["Redirecting to application...".encode()]
Reishin
  • 1,854
  • 18
  • 21
1

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)).

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75