2015-10-12 2 views
2

Я использую flask-jwt и flask-restfulКолба-JWT и колба-resftul обработки ошибок

Это как ошибки колба-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

В колбе:

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 

В колбе-успокоительная (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) 

В колбе -страстный (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) 
+0

Ниццы резюме, но что ваши вопрос? –

ответ

0

Я вижу, что вы пытаетесь поднять 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 
Смежные вопросы