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

gac*_*opu 6 python falconframework

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

主要.py

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

app.add_route('/', Resource())
Run Code Online (Sandbox Code Playgroud)

和授权

class AuthMiddleware(object):
    def process_request(self, req, resp):
        self.vvv = True
Run Code Online (Sandbox Code Playgroud)

和资源

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

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

Jav*_*ock 5

首先,您混淆了self含义。Self 仅影响类的实例,是向类添加属性的一种方式,因此 your self.vvvin与 your in your classAuthMiddleware是完全不同的属性。self.vvvResource

其次,您不需要了解资源中 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...
Run Code Online (Sandbox Code Playgroud)

查看 Falcon 页面示例