1
import httplib, mimetypes
3
"""Copied from the cookbook
6
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
9
def post_multipart(host, selector, fields, files):
11
Post fields and files to an http host as multipart/form-data.
12
fields is a sequence of (name, value) elements for regular form fields.
13
files is a sequence of (name, filename, value) elements for data to be
16
Return the server's response page.
18
content_type, body = encode_multipart_formdata(fields, files)
19
h = httplib.HTTP(host)
20
h.putrequest('POST', selector)
21
h.putheader('content-type', content_type)
22
h.putheader('content-length', str(len(body)))
25
errcode, errmsg, headers = h.getreply()
28
def encode_multipart_formdata(fields, files):
30
fields is a sequence of (name, value) elements for regular form fields.
31
files is a sequence of (name, filename, value) elements for data to be
34
Return (content_type, body) ready for httplib.HTTP instance
36
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
39
for (key, value) in fields:
40
L.append('--' + BOUNDARY)
41
L.append('Content-Disposition: form-data; name="%s"' % key)
44
for (key, filename, value) in files:
45
L.append('--' + BOUNDARY)
46
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
48
L.append('Content-Type: %s' % get_content_type(filename))
51
L.append('--' + BOUNDARY + '--')
54
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
55
return content_type, body
57
def get_content_type(filename):
58
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'