"""POST fields and files to an HTTP host as multipart/form-data. updates http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 to use HTTPConnection (former used HTTP) available from Python 2.0 to use for validate.py changed default mimetype returned by get_content_type() to 'text/html' so it is possible to validate files like .shtml, .php, .py etc delivered from a webserver (so with option UPLOAD=0 only!). """ __version__ = '1.4/ch' import httplib import mimetypes def post_multipart(host, selector, fields, files): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page. """ content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTPConnection(host) # h.set_debuglevel(1) headers = { 'User-Agent': 'pyvalidator/1.2', 'Content-Type': content_type } h.request('POST', selector, body, headers) res = h.getresponse() return res.status, res.reason, res.read() def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def get_content_type(filename): return mimetypes.guess_type(filename)[0] or 'text/html' # WAS: 'application/octet-stream'