简体   繁体   中英

Flask-restful - During handling of the above exception, another exception occurred

As part a Flask-restful API I have a login Resource:

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

There are 4 scenarios for login route:

  1. Email and Password are correct
  2. Email does not exist in the database - in this case the UnauthorizedError is raised correctly.
  3. Email exists but password is incorrect - in this case I have an issue (described below)
  4. Some other Error - InternalServerError is raised correctly.

So for number 3 - instead of getting an UnauthorizedError, I am getting an InternalServerError.

The if not authorized: statement is working correctly (If i put a print in there I can see it work). However for some reason I am getting the following when trying to raise the error:

During handling of the above exception, another exception occurred:

I came across this PEP article which seems to suggest changing to raise UnauthorizedError from None but the issue persists. Does anyone know how I can implement this successfully? Ideally I would like the same error to be raised from scenarios 2 and 3, otherwise there is a potential for someone to know whether or not an email exists in the database, from the errors they get back.

if 语句正在引发 UnAuthorized,但这种情况发生在异常中,您必须引发DoesNotExist 以使其能够在异常中引发 UnAuthorized。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM