Search code examples
pythonfalconframework

How to pass variable from middleware to resource in falcon?


I'm using Falcon, I need pass variable from middleware to resource, how can I do that?

main.py

app = falcon.API(middleware=[
    AuthMiddleware()
])

app.add_route('/', Resource())

and auth

class AuthMiddleware(object):
    def process_request(self, req, resp):
        self.vvv = True

and resource

class Resource(object):
    def __init__(self):
        self.vvv = False
    def on_get(self, req, resp):
        logging.info(self.vvv) #vvv is always False

why self.vvv is always false? I have changed it in middleware to true.


Solution

  • First of all you are confussing what self means. Self affects only to the instance of the class, is a way of adding attributes to your class, therefore your self.vvv in AuthMiddleware is a complete different attribute from your self.vvv in your class Resource.

    Second, you do not need to know anything from AuthMiddleware in your resource, thats why you want to use middleware. Middleware is a way to execute logic after or before each request. You need to implement your middleware so it raises Falcon exceptions or either modifies your request or response.

    For example, if you don't authorize a request, you must raise an exception like this:

    class AuthMiddleware(object):
    
        def process_request(self, req, resp):
            token = req.get_header('Authorization')
    
            challenges = ['Token type="Fernet"']
    
            if token is None:
                description = ('Please provide an auth token '
                               'as part of the request.')
    
                raise falcon.HTTPUnauthorized('Auth token required',
                                              description,
                                              challenges,
                                              href='http://docs.example.com/auth')
    
            if not self._token_is_valid(token):
                description = ('The provided auth token is not valid. '
                               'Please request a new token and try again.')
    
                raise falcon.HTTPUnauthorized('Authentication required',
                                              description,
                                              challenges,
                                              href='http://docs.example.com/auth')
    
        def _token_is_valid(self, token):
            return True  # Suuuuuure it's valid...
    

    Check Falcon page examples.