python Сани c Авторизация Decorator возвращает TypeError - PullRequest
0 голосов
/ 24 марта 2020

Я следовал руководству из официальной документации Sani c (здесь: https://sanic.readthedocs.io/en/latest/sanic/decorators.html) для валидационного декоратора JWT.

У меня есть декоратор:

def is_authorized():
    def decorator(f):
        @wraps(f)
        async def decorated_function(request, *args, **kwargs):
            try:
                identity = validate_jwt(request)
                request.ctx.identity = identity
                logger.info(f"[{request.ctx.request_id}]: successfully validated jwt token")

            except (MissingJwtException, MalformedTokenException) as e:
                logger.info(f"[{request.ctx.request_id}]: missing jwt in headers")
                return json({'status': 'ERROR', "status_code": 400,
                             "message": "missing or malformed authorization in header",
                             "transaction_id": request.ctx.request_id}, 400)
            except ExpiredSignatureError as e:
                logger.info(f"[{request.ctx.request_id}]: token is expired")
                return json({"status": "ERROR", "status_code": 401,
                             "message": "the token expired and is not longer valud",
                             "transaction_id": request.ctx.request_id}, 401)
            except DecodeError as e:
                logger.info(f"[{request.ctx.request_id}]: unable to decode jwt: {e}")
                return json({'status': 'ERROR', "status_code": 400, "message": "invalid token submitted",
                             "transaction_id": request.ctx.request_id}, 400)
            except WrongTokenException as e:
                logger.info(f"[{request.ctx.request_id}]: token seems not to be an access token: {e}")
                return json({'status': 'ERROR', "status_code": 403, "message": "invalid token submitted",
                             "transaction_id": request.ctx.request_id}, 403)
            except TypeError as e:
                logger.error(f"[{request.ctx.request_id}]: unkown error while decoding token: {e}")
                return json({'status': 'ERROR', "status_code": 500, "message": "internal server error",
                             "transaction_id": request.ctx.request_id}, 500)

            response = await f(request, *args, **kwargs)
            return response
        return decorated_function

    return decorator

Я использую декоратор следующим образом:

@is_authorized()
@validate_json(SHOP_CREATE_SCHEMA)
async def create(request):
    transaction_id = request.ctx.request_id
    logger.info(f"[{transaction_id}]: received new call for creating object")
    return json("pong")

Декоратор работает нормально и при любой ошибке, с разбором / проверкой jwt он возвращает данные. Проблема в успехе с этими строками: response = await f(request, *args, **kwargs). Я получаю сообщение об ошибке:

response = await f(request, *args, **kwargs)
TypeError: object HTTPResponse can't be used in 'await' expression

В чем проблема с этим, насколько я вижу, это также соответствует документации.

...