python - 如何将变量从中间件传递到猎鹰中的资源?
问题描述
我正在使用 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。
解决方案
首先,您混淆了是什么self
意思。Self 仅影响类的实例,是向您的类添加属性的一种方式,因此您的self.vvv
in与您的in 您的类AuthMiddleware
是完全不同的属性。self.vvv
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...
检查 Falcon 页面示例。
推荐阅读
- javascript - Angular7组件视图在数据操作上崩溃
- javascript - 使元素变宽,然后在达到某个点时变窄
- android - 如果我的apptheme的原色是白色,如何更改样式为轮廓的materialbutton的textcolor?
- python - 使用 python 2 类型注释指定实例变量的类型
- laravel - 记录所有身份验证错误 Laravel (nova)
- css - 为什么必须为所有 html 元素设置 grid-area 属性才能留下一个空单元格?
- java - 将 Jersey 客户端导入 Android 项目时出现重复的类错误
- java - 如何将每行的第一个元素移动到文本文件中该行的末尾?
- svn - 在解决方案资源管理器中复制文件时没有文件库
- c# - 更改复选框时如何订购 ListView