comparison 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
comparison
equal deleted inserted replaced
1183:6ef2c81581cd 1184:4e9d517503ae
16 # along with this program. If not, see <http://www.gnu.org/licenses/>. 16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 18
19 import httplib2 19 import httplib2
20 import json 20 import json
21 from urllib import urlencode 21 import sys
22
23 if (sys.version_info >= (3, 0)):
24 from urllib.parse import urlencode
25 else:
26 from urllib import urlencode
27
22 28
23 _credentials = None 29 _credentials = None
30
31
32 def _DecodeJson(s):
33 try:
34 if (sys.version_info >= (3, 0)):
35 return json.loads(s.decode())
36 else:
37 return json.loads(s)
38 except:
39 return s
40
24 41
25 def SetCredentials(username, password): 42 def SetCredentials(username, password):
26 global _credentials 43 global _credentials
27 _credentials = (username, password) 44 _credentials = (username, password)
28 45
40 _SetupCredentials(h) 57 _SetupCredentials(h)
41 resp, content = h.request(uri + d, 'GET') 58 resp, content = h.request(uri + d, 'GET')
42 if not (resp.status in [ 200 ]): 59 if not (resp.status in [ 200 ]):
43 raise Exception(resp.status) 60 raise Exception(resp.status)
44 elif not interpretAsJson: 61 elif not interpretAsJson:
45 return content 62 return content.decode()
46 else: 63 else:
47 try: 64 return _DecodeJson(content)
48 return json.loads(content)
49 except:
50 return content
51 65
52 66
53 def _DoPutOrPost(uri, method, data, contentType): 67 def _DoPutOrPost(uri, method, data, contentType):
54 h = httplib2.Http() 68 h = httplib2.Http()
55 _SetupCredentials(h) 69 _SetupCredentials(h)
70 headers = headers) 84 headers = headers)
71 85
72 if not (resp.status in [ 200, 302 ]): 86 if not (resp.status in [ 200, 302 ]):
73 raise Exception(resp.status) 87 raise Exception(resp.status)
74 else: 88 else:
75 try: 89 return _DecodeJson(content)
76 return json.loads(content)
77 except:
78 return content
79 90
80 91
81 def DoDelete(uri): 92 def DoDelete(uri):
82 h = httplib2.Http() 93 h = httplib2.Http()
83 _SetupCredentials(h) 94 _SetupCredentials(h)
84 resp, content = h.request(uri, 'DELETE') 95 resp, content = h.request(uri, 'DELETE')
85 96
86 if not (resp.status in [ 200 ]): 97 if not (resp.status in [ 200 ]):
87 raise Exception(resp.status) 98 raise Exception(resp.status)
88 else: 99 else:
89 try: 100 return _DecodeJson(content)
90 return json.loads(content)
91 except:
92 return content
93 101
94 102
95 def DoPut(uri, data = {}, contentType = ''): 103 def DoPut(uri, data = {}, contentType = ''):
96 return _DoPutOrPost(uri, 'PUT', data, contentType) 104 return _DoPutOrPost(uri, 'PUT', data, contentType)
97 105