首页 > 解决方案 > 如何将变量从中间件传递到猎鹰中的资源?

问题描述

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

主文件

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。

标签: pythonfalconframework

解决方案


首先,您混淆了是什么self意思。Self 仅影响类的实例,是向您的类添加属性的一种方式,因此您的self.vvvin与您的in 您的类AuthMiddleware是完全不同的属性。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...

检查 Falcon 页面示例


推荐阅读