Slide 25
Slide 25 text
import email.generator
import http.client
import io
import os
import shutil
def _encode_multipart_formdata(fields, files):
boundary = email.generator._make_boundary()
buf = io.BytesIO()
textwriter = io.TextIOWrapper(
buf, 'utf8', newline='', write_through=True)
for (key, value) in fields.items():
textwriter.write(
'--{boundary}\r\n'
'Content-Disposition: form-data; name="{key}"\r\n\r\n'
'{value}\r\n'.format(
boundary=boundary, key=key, value=value))
for (key, filepath, filename) in files:
if os.path.isfile(filepath):
textwriter.write(
'--{boundary}\r\n'
'Content-Disposition: form-data; name="{key}"; '
'filename="{filename}"\r\n'
'Content-Type: {content_type}\r\n\r\n'.format(
boundary=boundary, key=key, filename=filename,
content_type='application/octet-stream'))
with open(filepath, "rb") as f:
shutil.copyfileobj(f, buf)
textwriter.write('\r\n')
textwriter.write('--{}--\r\n\r\n'.format(boundary))
content_type = 'multipart/form-data; boundary={}'.format(boundary)
return content_type, buf.getvalue()
content_type, data = _encode_multipart_formdata(
fields={'key': 'value'},
files=[('filekey', 'test.py', 'test.py')]
)
headers = {
'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*',
'Connection': 'keep-alive',
'User-Agent': 'python-requests/2.7.0 CPython/2.7.10 Darwin 14.5.0',
'Content-Type': content_type,
'Content-Length': '{}'.format(len(data)),
}
c = http.client.HTTPSConnection('http2bin.org', 443)
c.request('POST', '/post', body=data, headers=headers)
resp = c.getresponse()
print(resp.read())