summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLars Wirzenius <liw@liw.fi>2019-01-24 10:15:06 +0200
committerLars Wirzenius <liw@liw.fi>2019-01-24 10:15:06 +0200
commitf7087038dcd6ca196ef8be418ee5848cea25ac91 (patch)
tree0228f4c6f78c39b9c2fcae00def003868292b8c6
parent478512d10ef861c05c7fb5e08b046d340636aef9 (diff)
downloadeffitool-f7087038dcd6ca196ef8be418ee5848cea25ac91.tar.gz
Refactor: DRY
-rwxr-xr-xeffitool51
1 files 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