Permalink
Browse files

Various minor changes

  • Loading branch information...
1 parent 7042fb6 commit 8d93b568dbeaa83080750bdcc4d67d3b147d5cad @edsrzf committed Mar 29, 2012
Showing with 25 additions and 43 deletions.
  1. +25 −43 iron_rest.py
View
@@ -1,27 +1,11 @@
import httplib
import time
-try:
- import json
-except ImportError:
- import simplejson as json
-
class TooManyRetriesError(Exception):
def __str__(self):
return repr("Max retries reached. Aborting.")
-
-class ServiceUnavailableError(httplib.HTTPException):
- def __str__(self):
- return repr("503: Service Unavailable")
-
-
class IronClient:
-
- default_headers = {
- "Accept": "application/json",
- }
-
def __init__(self, name, version, host, project_id, token, protocol,
port, api_version):
"""Prepare a Client that can make HTTP calls and return it.
@@ -50,19 +34,19 @@ def __init__(self, name, version, host, project_id, token, protocol,
self.protocol = protocol
self.port = int(port)
self.api_version = api_version
- self.headers = IronClient.default_headers
- self.headers["User-Agent"] = "%s (version: %s)" % (
- self.name, self.version)
- if self.token is not None:
+ self.headers = {
+ "Accept": "application/json",
+ "User-Agent": "%s (version: %s)" % (self.name, self.version)
+ }
+ if self.token:
self.headers["Authorization"] = "OAuth %s" % self.token
self.base_url = "%s://%s:%s/%s/" % (self.protocol, self.host,
self.port, self.api_version)
- if self.project_id is not None:
+ if self.project_id:
self.base_url += "projects/%s/" % self.project_id
- if self.protocol == "https":
- if not self.port == httplib.HTTPS_PORT:
- raise ValueError("Invalid port (%s) for an \
-HTTPS request. Want %s." % (self.port, httplib.HTTPS_PORT))
+ if self.protocol == "https" and self.port != httplib.HTTP_PORT:
+ raise ValueError("Invalid port (%s) for an HTTPS \
+ request. Want %s." % (self.port, httplib.HTTPS_PORT))
@classmethod
def retry(f, exceptionToCheck, tries=5, delay=1, backoff=2,
@@ -102,13 +86,11 @@ def f_retry(*args, **kwargs):
mdelay = delay
done = False
rv = None
- fail_msg = "Failed."
- success_msg = "Success! Returning."
while mtries > 0 and not done:
try_msg = "Attempt #%s" % (tries
- mtries + 1)
try:
- if logger is not None:
+ if logger:
logger.debug(try_msg)
rv = f(*args, **kwargs)
done = True
@@ -120,25 +102,23 @@ def f_retry(*args, **kwargs):
if mtries > 1:
try_s = " Retrying\
after %s seconds." % mdelay
- fail_msg = "Failed%s.%s" % (
- err_s, try_s)
- if logger is not None:
- logger.debug(fail_msg)
+ if logger:
+ logger.debug("Failed%s.%s", err_s, try_s)
rv = None
done = False
if mtries > 1:
time.sleep(mdelay)
mdelay *= backoff
mtries -= 1
if done:
- if logger is not None:
- logger.debug(success_msg)
+ if logger:
+ logger.debug("Success! Returning.")
return rv
raise exceptionToRaise
return f_retry
return deco_retry
- def request(self, url, method, body="", headers={}):
+ def request(self, url, method, body="", headers=None):
"""Execute an HTTP request and return a dict containing
the response and the response status code.
@@ -152,27 +132,29 @@ def request(self, url, method, body="", headers={}):
headers -- HTTP Headers to send with the request. Can
overwrite the defaults. Defaults to an empty dict.
"""
- headers = dict(list(headers.items()) +
- list(self.headers.items()))
+ if headers:
+ headers = dict(list(headers.items()) + list(self.headers.items()))
+ else:
+ headers = self.headers
+
if self.protocol == "http":
conn = httplib.HTTPConnection(self.host, self.port)
elif self.protocol == "https":
conn = httplib.HTTPSConnection(self.host, self.port)
else:
raise ValueError("Invalid protocol.")
- result = {"body": "", "status": None}
-
url = self.base_url + url
conn.request(method, url, body, headers)
resp = conn.getresponse()
+ result = {}
result["body"] = resp.read()
result["status"] = resp.status
conn.close()
return result
- def get(self, url, headers={}):
+ def get(self, url, headers=None):
"""Execute an HTTP GET request and return a dict containing
the response and the response status code.
@@ -185,7 +167,7 @@ def get(self, url, headers={}):
"""
return self.request(url=url, method="GET", headers=headers)
- def post(self, url, body="", headers={}):
+ def post(self, url, body="", headers=None):
"""Execute an HTTP POST request and return a dict containing
the response and the response status code.
@@ -202,7 +184,7 @@ def post(self, url, body="", headers={}):
return self.request(url=url, method="POST", body=body,
headers=headers)
- def delete(self, url, headers={}):
+ def delete(self, url, headers=None):
"""Execute an HTTP DELETE request and return a dict containing
the response and the response status code.
@@ -215,7 +197,7 @@ def delete(self, url, headers={}):
"""
return self.request(url=url, method="DELETE", headers=headers)
- def put(self, url, body="", headers={}):
+ def put(self, url, body="", headers=None):
"""Execute an HTTP PUT request and return a dict containing
the response and the response status code.

0 comments on commit 8d93b56

Please sign in to comment.