gpt4 book ai didi

Flask-jwt 和 Flask-resftul 错误处理

转载 作者:行者123 更新时间:2023-12-03 17:02:27 24 4
gpt4 key购买 nike

我正在使用 flask-jwtflask-restful

这就是 flask-jwt 处理错误的方式(取自其 github 存储库),但没有一个让我获取 JWTError 的参数。

if auth is None:
raise JWTError('Authorization Required', 'Authorization header was missing', 401, {
'WWW-Authenticate': 'JWT realm="%s"' % realm
})

parts = auth.split()

if parts[0].lower() != auth_header_prefix.lower():
raise JWTError('Invalid JWT header', 'Unsupported authorization type')
elif len(parts) == 1:
raise JWTError('Invalid JWT header', 'Token missing')
elif len(parts) > 2:
raise JWTError('Invalid JWT header', 'Token contains spaces')

try:
handler = _jwt.decode_callback
payload = handler(parts[1])
except SignatureExpired:
raise JWTError('Expired JWT', 'Token is expired', 401, {
"WWW-Authenticate": 'JWT realm="{0}"'.format(realm)
})
except BadSignature:
raise JWTError('Invalid JWT', 'Token is undecipherable')

_request_ctx_stack.top.current_user = user = _jwt.user_callback(payload)

if user is None:
raise JWTError('Invalid JWT', 'User does not exist')

以下是我尝试处理 JWTError 的不同方式

在 flask 中:

def handle_user_exception_again(e):
if isinstance(e, JWTError):
data = {'status_code': 1132, 'message': "JWTError already exists."}
return jsonify(data), e.status_code, e.headers
return e

app.handle_user_exception = handle_user_exception_again

在 flask-restful 中(handle_error)

class FlaskRestfulJwtAPI(Api):

def handle_error(self, e):
if isinstance(e, JWTError):
code = 400
data = {'status_code': code, 'message': "JWTError already exists."}
elif isinstance(e, KeyError):
code = 400
data = {'status_code': code, 'message': "KeyError already exists."}
else:
# Did not match a custom exception, continue normally
return super(FlaskRestfulJwtAPI, self).handle_error(e)
return self.make_response(data, code)

在 flask-restful (error_router) 中

class FlaskRestfulJwtAPI(Api):

def error_router(self, original_handler, e):
print(type(e))
if e is JWTError:#KeyError:
data = {
"code":400,
"message":"JWTError"
}
return jsonify(data), 400
elif isinstance(e,KeyError):
data = {
"code":400,
"message":"KeyError"
}
return jsonify(data), 400
else:
return super(FlaskRestfulJwtAPI, self).error_router(original_handler, e)

最佳答案

我看到您正在尝试从这些错误中引发 HTTPException,这有助于将它们返回给用户。要引发 HTTP 异常,您可以捕获所有错误,如果它们是 JWTError 的实例,您可以使用如下函数将它们转换为 HTTPException 的实例:

def convert_to_http_exception(e):
if isinstance(e, JWTError):
jwtdescription = e.error + ": " + e.description
http_exception = HTTPException(description=jwtdescription)
http_exception.code = e.status_code
return http_exception
else:
return e

关于Flask-jwt 和 Flask-resftul 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33083105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com