Last active
August 29, 2015 13:56
-
-
Save huyx/9226304 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
from urllib import urlencode | |
import os | |
FormFile = namedtuple('FormFile', 'filename, data') | |
def encode_form(fields, multipart=False, headers=None): | |
headers = headers or {} | |
if multipart: | |
boundary = "%s" % os.urandom(20).encode('hex') | |
start_boundary = '--' + boundary | |
end_boundary = start_boundary + '--' | |
headers = { 'Content-Type':'multipart/form-data; charset=utf-8; boundary=%s' % boundary } | |
lines = [] | |
for name, value in fields.iteritems(): | |
lines.append(start_boundary) | |
if isinstance(value, FormFile): | |
lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (name, value.filename)) | |
lines.append('Content-Type: application/octet-stream') | |
value = value.data | |
else: | |
lines.append('Content-Disposition: form-data; name="%s"' % name) | |
if not isinstance(value, basestring): | |
value = str(value) | |
lines.append('') | |
lines.append(value) | |
lines.append(end_boundary) | |
postdata = '\r\n'.join(lines) | |
else: | |
headers = { 'Content-Type':'application/x-www-form-urlencoded' } | |
postdata = urlencode(fields) | |
return headers, postdata | |
fields = OrderedDict([ | |
('a', 'a'), | |
('b', 'b'), | |
('file', FormFile('filename', 'file content ... ...')), | |
]) | |
header, postdata = encodeForm(fields) | |
url = 'http://...' | |
getPage(url, method='POST', headers=headers, postdata=postdata) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment