Package qubx :: Module http_post
[hide private]
[frames] | no frames]

Source Code for Module qubx.http_post

 1  import httplib 
 2  import mimetypes 
 3   
4 -def post_multipart(host, selector, fields, files, secure=True):
5 content_type, body = encode_multipart_formdata(fields, files) 6 h = secure and httplib.HTTPSConnection(host) or httplib.HTTPConnection(host) 7 headers = { 8 'User-Agent': 'INSERT USERAGENTNAME', 9 'Content-Type': content_type 10 } 11 h.request('POST', selector, body, headers) 12 res = h.getresponse() 13 return res.status, res.reason, res.read()
14 15
16 -def encode_multipart_formdata(fields, files):
17 """ 18 fields is a sequence of (name, value) elements for regular form fields. 19 files is a sequence of (name, filename, value) elements for data to be uploaded as files 20 Return (content_type, body) ready for httplib.HTTP instance 21 """ 22 BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' 23 CRLF = '\r\n' 24 L = [] 25 for (key, value) in fields: 26 L.append('--' + BOUNDARY) 27 L.append('Content-Disposition: form-data; name="%s"' % key) 28 L.append('') 29 L.append(value) 30 for (key, filename, value) in files: 31 L.append('--' + BOUNDARY) 32 L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) 33 L.append('Content-Type: %s' % get_content_type(filename)) 34 L.append('') 35 L.append(value) 36 L.append('--' + BOUNDARY + '--') 37 L.append('') 38 body = CRLF.join(L) 39 content_type = 'multipart/form-data; boundary=%s' % BOUNDARY 40 return content_type, body
41
42 -def get_content_type(filename):
43 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
44 45
46 -def get(host, selector, secure):
47 h = secure and httplib.HTTPSConnection(host) or httplib.HTTPConnection(host) 48 h.request('GET', selector) 49 res = h.getresponse() 50 return res.status, res.reason, res.read()
51