Skip to content
Browse files

Merge pull request #5 from iron-io/httplib

Use httplib
  • Loading branch information...
2 parents 3ae18e5 + 73ed6bf commit f36d166d58fad88190568b5e4fc9536542c87ac1 @paddyforan paddyforan committed Mar 8, 2012
Showing with 39 additions and 95 deletions.
  1. +37 −91 iron_mq.py
  2. +2 −4 test.py
View
128 iron_mq.py
@@ -1,6 +1,6 @@
# IronMQ For Python
+import httplib
import json
-import urllib2
import ConfigParser
@@ -12,27 +12,15 @@ def __str__(self):
return repr(self.message)
-class RequestWithMethod(urllib2.Request):
-
- """Wrap urllib2 to make DELETE requests possible."""
-
- def __init__(self, url, method, data=None, headers={},
- origin_req_host=None, unverifiable=False):
- self._method = method
- return urllib2.Request.__init__(self, url, data, headers,
- origin_req_host, unverifiable)
-
- def get_method(self):
- if self._method:
- return self._method
- else:
- return urllib2.Request.get_method(self)
-
-
class IronMQ:
DEFAULT_HOST = "mq-aws-us-east-1.iron.io"
USER_AGENT = "IronMQ Python v0.3"
+ __headers = {
+ "Accept": "application/json",
+ "User-Agent": "IronMQ Python v0.3",
+ }
+
def __init__(self, token=None, project_id=None, host=DEFAULT_HOST, port=443,
version=1, protocol='https', config=None, app_engine=False):
"""Prepare a configured instance of the API wrapper and return it.
@@ -46,8 +34,7 @@ def __init__(self, token=None, project_id=None, host=DEFAULT_HOST, port=443,
version -- The API version to use. Defaults to 1.
protocol -- The protocol to use. Defaults to https.
config -- The config file to draw config values from. Defaults to None.
- app_engine -- Whether to run in App Engine compatibility mode.
- Defaults to False.
+ app_engine -- Deprecated; does nothing
"""
self.token = token
self.version = version
@@ -56,7 +43,6 @@ def __init__(self, token=None, project_id=None, host=DEFAULT_HOST, port=443,
self.host = host
self.port = port
self.version = version
- self.app_engine = app_engine
if config is not None:
config_file = ConfigParser.RawConfigParser()
config_file.read(config)
@@ -89,80 +75,56 @@ def __init__(self, token=None, project_id=None, host=DEFAULT_HOST, port=443,
have a value")
self.url = "%s://%s:%s/%s/" % (self.protocol, self.host, self.port,
self.version)
- self.__setCommonHeaders()
- def __get(self, url, headers={}):
+ def __req(self, url, method, body=None, headers=None):
+ if headers is None:
+ headers = IronMQ.__headers
+ else:
+ headers = dict(headers.items() + IronMQ.__headers.items())
+ if self.protocol == "http":
+ conn = httplib.HTTPConnection(self.host, self.port)
+ elif self.protocol == "https":
+ conn = httplib.HTTPSConnection(self.host, self.port)
+
+ conn.request(method, url, body, headers)
+ resp = conn.getresponse()
+ body = resp.read()
+ conn.close()
+ return body
+
+ def __get(self, url, headers=None):
"""Execute an HTTP GET request and return the result.
Keyword arguments:
url -- The url to execute the request against. (Required)
- headers -- A dict of headers to merge with self.headers and send
+ headers -- A dict of headers to merge with IronMQ.__headers and send
with the request.
"""
- headers = dict(headers.items() + self.headers.items())
- if not self.app_engine:
- req = urllib2.Request(url, None, headers)
- ret = urllib2.urlopen(req)
- return ret.read()
- else:
- from google.appengine.api import urlfetch
- return urlfetch.fetch(url=url, method=urlfetch.GET,
- headers=headers).content
+ return self.__req(url, "GET", headers=headers)
- def __post(self, url, payload={}, headers={}):
+ def __post(self, url, payload=None, headers=None):
"""Execute an HTTP POST request and return the result.
Keyword arguments:
url -- The url to execute the request against. (Required)
payload -- A dict of key-value form data to send with the
request. Will be urlencoded.
- headers -- A dict of headers to merge with self.headers and send
+ headers -- A dict of headers to merge with IronMQ.__headers and send
with the request.
"""
- headers = dict(headers.items() + self.headers.items())
- if not self.app_engine:
- req = urllib2.Request(url, payload, headers)
- ret = urllib2.urlopen(req)
- return ret.read()
- else:
- from google.appengine.api import urlfetch
- if not isinstance(payload, basestring):
- import urllib
- payload = urllib.urlencode(payload)
- return urlfetch.fetch(url=url, payload=payload,
- method=urlfetch.POST, headers=headers).content
+ if headers is None:
+ headers = {"Content-Type": "application/json"}
+ return self.__req(url, "POST", body=payload, headers=headers)
- def __delete(self, url, payload={}, headers={}):
+ def __delete(self, url, headers=None):
"""Execute an HTTP DELETE request and return the result.
Keyword arguments:
url -- The url to execute the request against. (Required)
- payload -- A dict of key-value form data to send with the
- request. Will be urlencoded.
- headers -- A dict of headers to merge with self.headers and send
+ headers -- A dict of headers to merge with IronMQ.__headers and send
with the request.
"""
- headers = dict(headers.items() + self.headers.items())
- if not self.app_engine:
- req = RequestWithMethod(url=url, method='DELETE', data=payload,
- headers=headers)
- ret = urllib2.urlopen(req)
- s = ret.read()
- else:
- from google.appengine.api import urlfetch
- if not isinstance(payload, basestring):
- import urllib
- payload = urllib.urlencode(payload)
- return urlfetch.fetch(url=url, payload=payload,
- method=urlfetch.DELETE, headers=headers).content
-
- def __setCommonHeaders(self):
- """Modify your headers to match the JSON default values."""
- self.headers = {
- "Accept": "application/json",
- "Accept-Encoding": "gzip, deflate",
- "User-Agent": "IronMQ Python v0.3"
- }
+ return self.__req(url, "DELETE", headers=headers)
def getQueues(self, page=None, project_id=None):
"""Execute an HTTP request to get a list of queues and return it.
@@ -173,7 +135,6 @@ def getQueues(self, page=None, project_id=None):
page -- The 0-based page to get queues from. Defaults to None, which
omits the parameter.
"""
- self.__setCommonHeaders()
if project_id is None:
project_id = self.project_id
pageForURL = ""
@@ -194,7 +155,6 @@ def getQueueDetails(self, queue_name, project_id=""):
project_id -- The ID of the project the queue belongs to. Defaults to
the project ID set when initialising the wrapper.
"""
- self.__setCommonHeaders()
if project_id == "":
project_id = self.project_id
url = "%sprojects/%s/queues/%s?oauth=%s" % (self.url, project_id,
@@ -213,15 +173,12 @@ def deleteMessage(self, queue_name, message_id, project_id=None):
contains the message. Defaults to the project ID set
when initialising the wrapper.
"""
- self.__setCommonHeaders()
if project_id is None:
project_id = self.project_id
url = "%sprojects/%s/queues/%s/messages/%s?oauth=%s" % (self.url,
project_id, queue_name, message_id, self.token)
- req = RequestWithMethod(url, 'DELETE')
- ret = urllib2.urlopen(req)
- s = ret.read()
- return json.loads(s)
+ body = self.__delete(url)
+ return json.loads(body)
def postMessage(self, queue_name, messages=[], project_id=None):
"""Executes an HTTP request to create message on the queue.
@@ -233,7 +190,6 @@ def postMessage(self, queue_name, messages=[], project_id=None):
project_id -- The ID of the project the queue is under. Defaults to
the project ID set when the wrapper was initialised.
"""
- self.__setCommonHeaders()
if project_id is None:
project_id = self.project_id
url = "%sprojects/%s/queues/%s/messages?oauth=%s" % (self.url,
@@ -246,11 +202,8 @@ def postMessage(self, queue_name, messages=[], project_id=None):
msgs.append(message)
data = json.dumps({"messages": msgs})
dataLen = len(data)
- headers = self.headers
- headers['Content-Type'] = "application/json"
- headers['Content-Length'] = str(dataLen)
- s = self.__post(url=url, payload=data, headers=headers)
+ s = self.__post(url=url, payload=data)
ret = json.loads(s)
return ret
@@ -266,19 +219,12 @@ def getMessage(self, queue_name, max=None, project_id=None):
is to be pulled from. Defaults to the project ID set when
the wrapper was initialised.
"""
- self.__setCommonHeaders()
if project_id is None:
project_id = self.project_id
n = ""
if max is not None:
n = "&n=%s" % max
url = "%sprojects/%s/queues/%s/messages?oauth=%s%s" % (self.url,
project_id, queue_name, self.token, n)
- self.headers['Accept'] = "text/plain"
- try:
- del self.headers['Content-Type']
- del self.headers['Content-Length']
- except:
- pass
body = self.__get(url)
return json.loads(body)
View
6 test.py
@@ -15,10 +15,8 @@ def setUp(self):
self.mq = IronMQ(token=self.token, project_id=self.project_id)
def test_headers(self):
- self.assertEqual(self.mq.headers['Accept'], "application/json")
- self.assertEqual(self.mq.headers['Accept-Encoding'],
- "gzip, deflate")
- self.assertEqual(self.mq.headers['User-Agent'],
+ self.assertEqual(IronMQ._IronMQ__headers['Accept'], "application/json")
+ self.assertEqual(IronMQ._IronMQ__headers['User-Agent'],
"IronMQ Python v0.3")
def test_protocols(self):

0 comments on commit f36d166

Please sign in to comment.
Something went wrong with that request. Please try again.