From e19ecbf75cf22c61bf8bcf8a19740b83eb66549d Mon Sep 17 00:00:00 2001 From: Dean Lee Date: Fri, 6 Dec 2024 07:28:11 +0800 Subject: [PATCH] CommaApi: use context manager for response handling (#34118) use context manager for response handling --- tools/lib/api.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tools/lib/api.py b/tools/lib/api.py index 92a75d2a3b..c2e1b1a8cd 100644 --- a/tools/lib/api.py +++ b/tools/lib/api.py @@ -10,16 +10,16 @@ class CommaApi: self.session.headers['Authorization'] = 'JWT ' + token def request(self, method, endpoint, **kwargs): - resp = self.session.request(method, API_HOST + '/' + endpoint, **kwargs) - resp_json = resp.json() - if isinstance(resp_json, dict) and resp_json.get('error'): - if resp.status_code in [401, 403]: - raise UnauthorizedError('Unauthorized. Authenticate with tools/lib/auth.py') + with self.session.request(method, API_HOST + '/' + endpoint, **kwargs) as resp: + resp_json = resp.json() + if isinstance(resp_json, dict) and resp_json.get('error'): + if resp.status_code in [401, 403]: + raise UnauthorizedError('Unauthorized. Authenticate with tools/lib/auth.py') - e = APIError(str(resp.status_code) + ":" + resp_json.get('description', str(resp_json['error']))) - e.status_code = resp.status_code - raise e - return resp_json + e = APIError(str(resp.status_code) + ":" + resp_json.get('description', str(resp_json['error']))) + e.status_code = resp.status_code + raise e + return resp_json def get(self, endpoint, **kwargs): return self.request('GET', endpoint, **kwargs)