comparison Resources/Samples/Python/RestToolbox.py @ 346:107da6a8c630

credentials in python rest toolbox
author jodogne
date Wed, 23 Jan 2013 13:29:47 +0100
parents b51c67f28b33
children 4d76fce206ef
comparison
equal deleted inserted replaced
345:795ce0fa8e8a 346:107da6a8c630
1 import httplib2 1 import httplib2
2 import json 2 import json
3 from urllib import urlencode 3 from urllib import urlencode
4
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])
4 15
5 def DoGet(uri, data = {}): 16 def DoGet(uri, data = {}):
6 d = '' 17 d = ''
7 if len(data.keys()) > 0: 18 if len(data.keys()) > 0:
8 d = '?' + urlencode(data) 19 d = '?' + urlencode(data)
9 20
10 h = httplib2.Http() 21 h = httplib2.Http()
22 _SetupCredentials(h)
11 resp, content = h.request(uri + d, 'GET') 23 resp, content = h.request(uri + d, 'GET')
12 if not (resp.status in [ 200 ]): 24 if not (resp.status in [ 200 ]):
13 raise Exception(resp.status) 25 raise Exception(resp.status)
14 else: 26 else:
15 try: 27 try:
18 return content 30 return content
19 31
20 32
21 def _DoPutOrPost(uri, method, data, contentType): 33 def _DoPutOrPost(uri, method, data, contentType):
22 h = httplib2.Http() 34 h = httplib2.Http()
35 _SetupCredentials(h)
23 36
24 if isinstance(data, str): 37 if isinstance(data, str):
25 body = data 38 body = data
26 if len(contentType) != 0: 39 if len(contentType) != 0:
27 headers = { 'content-type' : contentType } 40 headers = { 'content-type' : contentType }
43 return content 56 return content
44 57
45 58
46 def DoDelete(uri): 59 def DoDelete(uri):
47 h = httplib2.Http() 60 h = httplib2.Http()
61 _SetupCredentials(h)
48 resp, content = h.request(uri, 'DELETE') 62 resp, content = h.request(uri, 'DELETE')
63
49 if not (resp.status in [ 200 ]): 64 if not (resp.status in [ 200 ]):
50 raise Exception(resp.status) 65 raise Exception(resp.status)
51 else: 66 else:
52 try: 67 try:
53 return json.loads(content) 68 return json.loads(content)