summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorScott Bahling <sbahling@suse.de>2016-03-03 02:10:35 +0100
committerScott Bahling <sbahling@suse.de>2016-03-03 02:10:35 +0100
commit3f1196fbc783b77af647cebd99400edcf465dc9c (patch)
tree74b7e4256a12c79bcc24c8a791ca7aa5eca9f638
parent622b176e622e96742610bbaf07cab645e6b208a1 (diff)
downloadobsapi-3f1196fbc783b77af647cebd99400edcf465dc9c.tar.gz
obsapi-3f1196fbc783b77af647cebd99400edcf465dc9c.tar.xz
obsapi-3f1196fbc783b77af647cebd99400edcf465dc9c.zip
Add ObsHttpApi class
-rw-r--r--obsapi/httpapi.py104
1 files changed, 104 insertions, 0 deletions
diff --git a/obsapi/httpapi.py b/obsapi/httpapi.py
new file mode 100644
index 0000000..96d58bc
--- /dev/null
+++ b/obsapi/httpapi.py
@@ -0,0 +1,104 @@
+# -*- coding: utf-8 -*-
+#
+import requests
+from requests.auth import HTTPBasicAuth
+
+try:
+ import osc.conf as osc_conf
+ osc_conf.get_config()
+except:
+ osc_conf = None
+
+DEFAULTAPIURL = 'https://api.opensuse.org'
+
+
+class ObsHttpApi(object):
+
+ default_xml = '<None/>'
+ rootapi = '/'
+
+ def __init__(self, apiurl=None):
+ self.apiurl = apiurl or DEFAULTAPIURL
+ self.__get_auth()
+ self._response = None
+ self.retries = 3
+ self.verify_ssl = True
+
+ def __get_auth(self):
+ conf = {}
+ if osc_conf:
+ try:
+ conf = osc_conf.get_apiurl_api_host_options(self.apiurl)
+ except:
+ pass
+
+ user = conf.get('user', None)
+ password = conf.get('pass', None)
+ if user and password:
+ self.auth = HTTPBasicAuth(user, password)
+ else:
+ self.auth = None
+
+ def __api_get(self, api, params=None):
+
+ def try_get():
+ url = '{0}{1}{2}'.format(self.apiurl, self.rootapi, api)
+ print(url)
+ r = requests.get(url,
+ auth=self.auth,
+ params=params,
+ verify=self.verify_ssl)
+ self._response = r
+ return r
+
+ for attempt in range(self.retries):
+ r = try_get()
+ if self.success:
+ return r
+ print("Failed: %s" % self.response)
+ print("retry: %s" % (attempt + 1))
+
+ if self.retries == 0:
+ r = try_get()
+
+ return r
+
+ def __api_put(self, api, data):
+
+ url = '{0}{1}{2}'.format(self.apiurl, self.rootapi, api)
+ r = requests.put(url,
+ auth=self.auth,
+ data=data,
+ verify=self.verify_ssl)
+ self._response = r
+
+ return r
+
+ @property
+ def response(self):
+ '''Return requests response from last api query'''
+ return self._response
+
+ @property
+ def success(self):
+ '''Return True if last api query was successful, else
+ return False'''
+ return self._response.status_code == requests.codes.ok
+
+ def __api(self, *args):
+ args = [elem for elem in args if elem]
+ return '/'.join(['{}'] * len(args)).format(*args)
+
+ def get(self, *args, **params):
+ api = self.__api(*args)
+ r = self.__api_get(api, params=params)
+ if not self.success:
+ print self.response
+ return self.default_xml
+
+ return r.text
+
+ def put(self, args, data):
+ api = self.__api(*args)
+ r = self.__api_put(api, data)
+ return r