diff --git a/railib/rest.py b/railib/rest.py index 379142b..2b3d199 100644 --- a/railib/rest.py +++ b/railib/rest.py @@ -194,14 +194,14 @@ def _request_access_token(ctx: Context, url: str) -> AccessToken: data=data, ) _print_request(req) - rsp = _urlopen_with_retry(req, ctx.retries) - result = json.loads(rsp.read()) - token = result.get(ACCESS_KEY_TOKEN_KEY, None) - - if token is not None: - expires_in = result.get(EXPIRES_IN_KEY, None) - scope = result.get(SCOPE, None) - return AccessToken(token, scope, expires_in) + with _urlopen_with_retry(req, ctx.retries) as rsp: + result = json.loads(rsp.read()) + token = result.get(ACCESS_KEY_TOKEN_KEY, None) + + if token is not None: + expires_in = result.get(EXPIRES_IN_KEY, None) + scope = result.get(SCOPE, None) + return AccessToken(token, scope, expires_in) raise Exception("failed to get the access token")