How to pass variable from middleware to resource in falcon?
Asked Answered
C

2

6

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.

Chichi answered 7/8, 2018 at 6:20 Comment(0)
M
5

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.

Motheaten answered 22/9, 2018 at 17:14 Comment(0)
G
3

From https://falcon.readthedocs.io/en/stable/api/middleware.html:

In order to pass data from a middleware function to a resource function use the req.context and resp.context objects. These context objects are intended to hold request and response data specific to your app as it passes through the framework.

class AuthMiddleware(object):
    def process_request(self, req, resp):
        # self.vvv = True       # -
        req.context.vvv = True  # +
class Resource(object):
    # def __init__(self):   # -
    #     self.vvv = False  # -
    def on_get(self, req, resp):
        # logging.info(self.vvv)       # -
        logging.info(req.context.vvv)  # +

You should not use the attributes on middleware and resource instances for your request data. Since you only instantiate them once, modifying their attributes is generally not thread-safe.

Gattis answered 1/3, 2022 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.