Flaskrestful在处理上述异常期间,发生了另一个异常

2024-10-01 07:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

作为Flask restful API的一部分,我有一个登录资源:

class LoginApi(Resource):
    def post(self):
        try:
            body = request.get_json()
            user = User.objects.get(email=body.get('email'))
            authorized = user.check_password(body.get('password'))
            if not authorized:
                raise UnauthorizedError
            expires = datetime.timedelta(days=7)
            access_token = create_access_token(identity=str(user.id), expires_delta=expires)
            return {'token': access_token}, 200
        except DoesNotExist:
            raise UnauthorizedError
        except Exception as e:
            raise InternalServerError

登录路由有4种场景:

  1. 电子邮件和密码是正确的
  2. 数据库中不存在电子邮件-在这种情况下,将正确引发UnauthorizedError
  3. 电子邮件存在,但密码不正确-在这种情况下,我有一个问题(如下所述)
  4. 其他一些错误-正确引发InternalServerError

因此,对于第3个问题,我得到的不是未经授权的错误,而是一个InternalServerError

if not authorized:语句工作正常(如果我在其中放入打印,我可以看到它工作)。但是,由于某些原因,我在尝试提出错误时得到以下信息:

During handling of the above exception, another exception occurred:

我遇到了this PEP article,它似乎建议改为raise UnauthorizedError from None,但问题仍然存在。有人知道我如何才能成功地实现这一点吗?理想情况下,我希望在场景2和场景3中出现相同的错误,否则可能会有人从返回的错误中知道数据库中是否存在电子邮件


Tags: tokengetaccess电子邮件email错误场景情况