Skip to content

Commit a326f58

Browse files
committed
Porting to python3
Note that it uses six for that. I did not check if a previous release than 1.10 was working. Also I only tried it with requests.
1 parent 40dbeb3 commit a326f58

File tree

3 files changed

+24
-22
lines changed

3 files changed

+24
-22
lines changed

clever/__init__.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# Borrows heavily from the Python bindings for the Stripe API
55

66
# Imports
7+
from __future__ import print_function
78
import logging
89
import os
910
import platform
@@ -15,12 +16,12 @@
1516
import types
1617
import base64
1718
import pkg_resources
18-
19+
import six
1920
# Use cStringIO if ita's available. Otherwise, StringIO is fine.
2021
try:
2122
import cStringIO as StringIO
2223
except ImportError:
23-
import StringIO
24+
from six import StringIO
2425

2526
# - Requests is the preferred HTTP library
2627
# - Google App Engine has urlfetch
@@ -50,8 +51,8 @@
5051
pass
5152
else:
5253
if major == 0 and (minor < 8 or (minor == 8 and patch < 8)):
53-
print >>sys.stderr, 'Warning: the Clever library requires that your Python "requests" library has a version no older than 0.8.8, but your "requests" library has version %s. Clever will fall back to an alternate HTTP library, so everything should work, though we recommend upgrading your "requests" library. If you have any questions, please contact [email protected]. (HINT: running "pip install -U requests" should upgrade your requests library to the latest version.)' % (
54-
version, )
54+
print('Warning: the Clever library requires that your Python "requests" library has a version no older than 0.8.8, but your "requests" library has version %s. Clever will fall back to an alternate HTTP library, so everything should work, though we recommend upgrading your "requests" library. If you have any questions, please contact [email protected]. (HINT: running "pip install -U requests" should upgrade your requests library to the latest version.)' % (
55+
version, ), file=sys.stderr)
5556
_httplib = None
5657

5758
if not _httplib:
@@ -65,16 +66,16 @@
6566
try:
6667
import urllib2
6768
_httplib = 'urllib2'
68-
print >>sys.stderr, "Warning: the Clever library is falling back to urllib2 because pycurl isn't installed. urllib2's SSL implementation doesn't verify server certificates. For improved security, we suggest installing pycurl."
69+
print("Warning: the Clever library is falling back to urllib2 because pycurl isn't installed. urllib2's SSL implementation doesn't verify server certificates. For improved security, we suggest installing pycurl.", file=sys.stderr)
6970
except ImportError:
7071
pass
7172

7273
if not _httplib:
7374
raise ImportError(
7475
"Clever requires one of pycurl, Google App Engine's urlfetch, or urllib2. If you are on a platform where none of these libraries are available, please let us know at [email protected].")
7576

76-
from version import VERSION
77-
import importer
77+
from .version import VERSION
78+
from . import importer
7879
json = importer.import_json()
7980

8081
logger = logging.getLogger('clever')
@@ -151,7 +152,7 @@ def convert_to_clever_object(klass, resp, auth):
151152
return [convert_to_clever_object(klass, i, auth) for i in resp['data']]
152153
elif isinstance(resp['data'], dict):
153154
return klass.construct_from(resp['data'].copy(), auth)
154-
elif isinstance(resp, basestring) or isinstance(resp, list) or isinstance(resp, dict) or isinstance(resp, bool):
155+
elif isinstance(resp, six.string_types) or isinstance(resp, list) or isinstance(resp, dict) or isinstance(resp, bool):
155156
return resp
156157
else:
157158
raise Exception('DONT KNOW WHAT TO DO WITH {0}'.format(resp))
@@ -193,7 +194,7 @@ def _objects_to_ids(cls, d):
193194
return d.id
194195
elif isinstance(d, dict):
195196
res = {}
196-
for k, v in d.iteritems():
197+
for k, v in six.iteritems(d):
197198
res[k] = cls._objects_to_ids(v)
198199
return res
199200
else:
@@ -261,7 +262,7 @@ def request_raw(self, meth, url, params={}):
261262
['uname', lambda: ' '.join(platform.uname())]]:
262263
try:
263264
val = func()
264-
except Exception, e:
265+
except Exception as e:
265266
val = "!! %s" % e
266267
ua[attr] = val
267268

@@ -325,7 +326,7 @@ def requests_request(self, meth, abs_url, headers, params):
325326
result = requests.request(meth, abs_url,
326327
headers=headers, data=data, timeout=80,
327328
verify=CLEVER_CERTS)
328-
except TypeError, e:
329+
except TypeError as e:
329330
raise TypeError(
330331
'Warning: It looks like your installed version of the "requests" library is not compatible with Clever\'s usage thereof. (HINT: The most likely cause is that your "requests" library is out of date. You can fix that by running "pip install -U requests".) The underlying error was: %s' % (e, ))
331332

@@ -335,7 +336,7 @@ def requests_request(self, meth, abs_url, headers, params):
335336
content = result.content
336337
status_code = result.status_code
337338
headers = result.headers
338-
except Exception, e:
339+
except Exception as e:
339340
# Would catch just requests.exceptions.RequestException, but can
340341
# also raise ValueError, RuntimeError, etc.
341342
self.handle_requests_error(e)
@@ -356,8 +357,8 @@ def handle_requests_error(self, e):
356357
raise APIConnectionError(msg)
357358

358359
def pycurl_request(self, meth, abs_url, headers, params):
359-
s = StringIO.StringIO()
360-
rheader = StringIO.StringIO()
360+
s = StringIO()
361+
rheader = StringIO()
361362
curl = pycurl.Curl()
362363

363364
meth = meth.lower()
@@ -385,7 +386,7 @@ def pycurl_request(self, meth, abs_url, headers, params):
385386
curl.setopt(pycurl.NOSIGNAL, 1)
386387
curl.setopt(pycurl.CONNECTTIMEOUT, 30)
387388
curl.setopt(pycurl.TIMEOUT, 80)
388-
curl.setopt(pycurl.HTTPHEADER, ['%s: %s' % (k, v) for k, v in headers.iteritems()])
389+
curl.setopt(pycurl.HTTPHEADER, ['%s: %s' % (k, v) for k, v in six.iteritems(headers)])
389390
curl.setopt(pycurl.HEADERFUNCTION, rheader.write)
390391
if verify_ssl_certs:
391392
curl.setopt(pycurl.CAINFO, CLEVER_CERTS)
@@ -394,7 +395,7 @@ def pycurl_request(self, meth, abs_url, headers, params):
394395

395396
try:
396397
curl.perform()
397-
except pycurl.error, e:
398+
except pycurl.error as e:
398399
self.handle_pycurl_error(e)
399400
return {'body': s.getvalue(), 'headers': rheader.getvalue(), 'code': curl.getinfo(pycurl.RESPONSE_CODE)}
400401

@@ -438,7 +439,7 @@ def urlfetch_request(self, meth, abs_url, headers, params):
438439

439440
try:
440441
result = urlfetch.fetch(**args)
441-
except urlfetch.Error, e:
442+
except urlfetch.Error as e:
442443
self.handle_urlfetch_error(e, abs_url)
443444
return {'body': result.content, 'headers': result.headers, 'code': result.status_code}
444445

@@ -480,11 +481,11 @@ def urllib2_request(self, meth, abs_url, headers, params):
480481
rbody = response.read()
481482
rheader = response.info()
482483
rcode = response.code
483-
except urllib2.HTTPError, e:
484+
except urllib2.HTTPError as e:
484485
rcode = e.code
485486
rheader = None
486487
rbody = e.read()
487-
except (urllib2.URLError, ValueError), e:
488+
except (urllib2.URLError, ValueError) as e:
488489
self.handle_urllib2_error(e, abs_url)
489490
return {'body': rbody, 'headers': rheader, 'code': rcode}
490491

@@ -607,7 +608,7 @@ def refresh_from(self, values, auth, partial=False):
607608
self._transient_values.add(k)
608609
self._unsaved_values.discard(k)
609610

610-
for k, v in values.iteritems():
611+
for k, v in six.iteritems(values):
611612
if k in self._permanent_attributes:
612613
continue
613614
self.__dict__[k] = convert_to_clever_object(self, v, auth)
@@ -617,7 +618,7 @@ def refresh_from(self, values, auth, partial=False):
617618

618619
def __repr__(self):
619620
id_string = ''
620-
if isinstance(self.get('id'), basestring):
621+
if isinstance(self.get('id'), six.string_types):
621622
id_string = ' id=%s' % self.get('id').encode('utf8')
622623

623624
return '<%s%s at %s> JSON: %s' % (type(self).__name__, id_string, hex(id(self)), json.dumps(self.to_dict(), sort_keys=True, indent=2, cls=CleverObjectEncoder))

clever/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
import pkg_resources
22

33
version_file = pkg_resources.resource_stream(__name__, "VERSION")
4-
VERSION = version_file.readline().strip()
4+
VERSION = version_file.readline().strip().decode()

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
httmock>=1.2.2
22
requests>=0.8.8
3+
six>=1.10.0

0 commit comments

Comments
 (0)