如何将变量从中间件传递到猎鹰中的资源?

How to pass variable from middleware to resource in falcon?

我正在使用 Falcon,我需要将变量从中间件传递到资源,我该怎么做?

main.py

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

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

和授权

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

和资源

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

为什么 self.vvv 总是错误的?我已经在中间件中将其更改为 true。

首先你混淆了self的意思。自我仅影响 class 的实例,是一种向 class 添加属性的方法,因此 AuthMiddleware 中的 self.vvv 是与 [=] 完全不同的属性12=] 在你的 class Resource.

其次,您不需要从资源中的 AuthMiddleware 了解任何信息,这就是您想要使用中间件的原因。中间件是一种在每个请求之后或之前执行逻辑的方法。您需要实施您的中间件,以便它引发 Falcon 异常或修改您的请求或响应。

例如,如果您不授权请求,则必须像这样引发异常:

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

检查猎鹰页面 examples

来自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)  # +

您不应将中间件和资源实例上的属性用于您的请求数据。由于只实例化一次,修改它们的属性一般不会thread-safe.