comparison Resources/Samples/Python/RestToolbox.py @ 340:61f6a3d66b85

changes loop sample
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 17 Jan 2013 15:54:02 +0100
parents
children b51c67f28b33
comparison
equal deleted inserted replaced
339:639272ef7615 340:61f6a3d66b85
1 import hashlib
2 import httplib2
3 import json
4 import os.path
5 import Image
6 import zipfile
7 from urllib import urlencode
8
9 def DoGet(uri, data = {}):
10 d = ''
11 if len(data.keys()) > 0:
12 d = '?' + urlencode(data)
13
14 h = httplib2.Http()
15 resp, content = h.request(uri + d, 'GET')
16 if not (resp.status in [ 200 ]):
17 raise Exception(resp.status)
18 else:
19 try:
20 return json.loads(content)
21 except:
22 return content
23
24
25 def _DoPutOrPost(uri, method, data, contentType):
26 h = httplib2.Http()
27
28 if isinstance(data, str):
29 body = data
30 if len(contentType) != 0:
31 headers = { 'content-type' : contentType }
32 else:
33 body = json.dumps(data)
34 headers = { 'content-type' : 'application/json' }
35
36 resp, content = h.request(
37 uri, method,
38 body = body,
39 headers = headers)
40
41 if not (resp.status in [ 200, 302 ]):
42 raise Exception(resp.status)
43 else:
44 try:
45 return json.loads(content)
46 except:
47 return content
48
49
50 def DoDelete(uri):
51 h = httplib2.Http()
52 resp, content = h.request(uri, 'DELETE')
53 if not (resp.status in [ 200 ]):
54 raise Exception(resp.status)
55 else:
56 try:
57 return json.loads(content)
58 except:
59 return content
60
61
62 def DoPut(uri, data = {}, contentType = ''):
63 return _DoPutOrPost(uri, 'PUT', data, contentType)
64
65
66 def DoPost(uri, data = {}, contentType = ''):
67 return _DoPutOrPost(uri, 'POST', data, contentType)