From f7087038dcd6ca196ef8be418ee5848cea25ac91 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Thu, 24 Jan 2019 10:15:06 +0200 Subject: Refactor: DRY --- effitool | 51 ++++++++++++++++++++++++--------------------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/effitool b/effitool index 74da7be..2bff76c 100755 --- a/effitool +++ b/effitool @@ -69,20 +69,31 @@ class HTTPAPI: def url(self, path): return '{}{}'.format(self._url, path) + def get_json(self, r): + ok = (http.HTTPStatus.OK, http.HTTPStatus.CREATED) + + status = r.getcode() + if status not in ok: + raise Exception('Got HTTP status {}'.format(status)) + + info = r.info() + ct = info.get_content_type() + if ct != JSON: + raise Exception('Response is not JSON: {}'.ct) + + body = r.read() + return json.loads(body) + def get(self, path): url = self.url(path) with urllib.request.urlopen(url) as r: - status = r.getcode() - if status != http.HTTPStatus.OK: - raise Exception('Got HTTP status {}'.format(status)) - - info = r.info() - ct = info.get_content_type() - if ct != JSON: - raise Exception('Response is not JSON: {}'.ct) + return self.get_json(r) - body = r.read() - return json.loads(body) + def get_access_token(self, client_id, client_secret, scopes): + obj = self.post_form( + '/token', client_id, client_secret, + grant_type='client_credentials', scope=' '.join(scopes)) + return obj['access_token'] def post_form(self, path, user, password, **kwargs): url = self.url(path) @@ -97,18 +108,7 @@ class HTTPAPI: req = urllib.request.Request( url, data=data, headers=headers, method='POST') r = urllib.request.urlopen(req) - - status = r.getcode() - if status != http.HTTPStatus.OK: - raise Exception('Got HTTP status {}'.format(status)) - - info = r.info() - ct = info.get_content_type() - if ct != JSON: - raise Exception('Response is not JSON: {}'.ct) - - body = r.read() - return json.loads(body) + return self.get_json(r) def parse_url(self, url): parse = urllib.parse.urlparse(url) @@ -157,11 +157,8 @@ def register_client(args, config): client_id = server['client_id'] client_secret = server['client_secret'] api = HTTPAPI(url) - r = api.post_form( - '/token', client_id, client_secret, - grant_type='client_credentials', scope='xxx') - token = r['access_token'] - + token = api.get_access_token(client_id, client_secret, ['xxx']) + print(token) print('NEED TO ACTUALLY CREATE CLIENT HERE') assert 0 -- cgit v1.2.1