340
|
1 import httplib2
|
|
2 import json
|
|
3 from urllib import urlencode
|
|
4
|
346
|
5 _credentials = None
|
|
6
|
|
7 def SetCredentials(username, password):
|
|
8 global _credentials
|
|
9 _credentials = (username, password)
|
|
10
|
|
11 def _SetupCredentials(h):
|
|
12 global _credentials
|
|
13 if _credentials != None:
|
|
14 h.add_credentials(_credentials[0], _credentials[1])
|
|
15
|
424
|
16 def DoGet(uri, data = {}, interpretAsJson = True):
|
340
|
17 d = ''
|
|
18 if len(data.keys()) > 0:
|
|
19 d = '?' + urlencode(data)
|
|
20
|
|
21 h = httplib2.Http()
|
346
|
22 _SetupCredentials(h)
|
340
|
23 resp, content = h.request(uri + d, 'GET')
|
|
24 if not (resp.status in [ 200 ]):
|
|
25 raise Exception(resp.status)
|
424
|
26 elif not interpretAsJson:
|
|
27 return content
|
340
|
28 else:
|
|
29 try:
|
|
30 return json.loads(content)
|
|
31 except:
|
|
32 return content
|
|
33
|
|
34
|
|
35 def _DoPutOrPost(uri, method, data, contentType):
|
|
36 h = httplib2.Http()
|
346
|
37 _SetupCredentials(h)
|
340
|
38
|
|
39 if isinstance(data, str):
|
|
40 body = data
|
|
41 if len(contentType) != 0:
|
|
42 headers = { 'content-type' : contentType }
|
354
|
43 else:
|
|
44 headers = { 'content-type' : 'text/plain' }
|
340
|
45 else:
|
|
46 body = json.dumps(data)
|
|
47 headers = { 'content-type' : 'application/json' }
|
|
48
|
|
49 resp, content = h.request(
|
|
50 uri, method,
|
|
51 body = body,
|
|
52 headers = headers)
|
|
53
|
|
54 if not (resp.status in [ 200, 302 ]):
|
|
55 raise Exception(resp.status)
|
|
56 else:
|
|
57 try:
|
|
58 return json.loads(content)
|
|
59 except:
|
|
60 return content
|
|
61
|
|
62
|
|
63 def DoDelete(uri):
|
|
64 h = httplib2.Http()
|
346
|
65 _SetupCredentials(h)
|
340
|
66 resp, content = h.request(uri, 'DELETE')
|
346
|
67
|
340
|
68 if not (resp.status in [ 200 ]):
|
|
69 raise Exception(resp.status)
|
|
70 else:
|
|
71 try:
|
|
72 return json.loads(content)
|
|
73 except:
|
|
74 return content
|
|
75
|
|
76
|
|
77 def DoPut(uri, data = {}, contentType = ''):
|
|
78 return _DoPutOrPost(uri, 'PUT', data, contentType)
|
|
79
|
|
80
|
|
81 def DoPost(uri, data = {}, contentType = ''):
|
|
82 return _DoPutOrPost(uri, 'POST', data, contentType)
|