diff Resources/Samples/Python/RestToolbox.py @ 1184:4e9d517503ae

port to Python3
author Sebastien Jodogne <s.jodogne@gmail.com>
date Fri, 10 Oct 2014 09:13:48 +0200
parents 44382c8bcd15
children 6e7e5ed91c2d
line wrap: on
line diff
--- a/Resources/Samples/Python/RestToolbox.py	Fri Oct 10 08:52:56 2014 +0200
+++ b/Resources/Samples/Python/RestToolbox.py	Fri Oct 10 09:13:48 2014 +0200
@@ -18,10 +18,27 @@
 
 import httplib2
 import json
-from urllib import urlencode
+import sys
+
+if (sys.version_info >= (3, 0)):
+    from urllib.parse import urlencode
+else:
+    from urllib import urlencode
+
 
 _credentials = None
 
+
+def _DecodeJson(s):
+    try:
+        if (sys.version_info >= (3, 0)):
+            return json.loads(s.decode())
+        else:
+            return json.loads(s)
+    except:
+        return s
+
+
 def SetCredentials(username, password):
     global _credentials
     _credentials = (username, password)
@@ -42,12 +59,9 @@
     if not (resp.status in [ 200 ]):
         raise Exception(resp.status)
     elif not interpretAsJson:
-        return content
+        return content.decode()
     else:
-        try:
-            return json.loads(content)
-        except:
-            return content
+        return _DecodeJson(content)
 
 
 def _DoPutOrPost(uri, method, data, contentType):
@@ -72,10 +86,7 @@
     if not (resp.status in [ 200, 302 ]):
         raise Exception(resp.status)
     else:
-        try:
-            return json.loads(content)
-        except:
-            return content
+        return _DecodeJson(content)
 
 
 def DoDelete(uri):
@@ -86,10 +97,7 @@
     if not (resp.status in [ 200 ]):
         raise Exception(resp.status)
     else:
-        try:
-            return json.loads(content)
-        except:
-            return content
+        return _DecodeJson(content)
 
 
 def DoPut(uri, data = {}, contentType = ''):