file_upload demo: write multi-part framing in one call

This commit is contained in:
Pierce Lopez 2017-09-12 16:57:50 -04:00
parent ab42d83714
commit e92aa20f2d
1 changed files with 8 additions and 7 deletions

View File

@ -34,13 +34,15 @@ def multipart_producer(boundary, filenames, write):
for filename in filenames:
filename_bytes = filename.encode()
yield write(b'--%s\r\n' % (boundary_bytes,))
yield write(b'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' %
(filename_bytes, filename_bytes))
mtype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
yield write(b'Content-Type: %s\r\n' % (mtype.encode(),))
yield write(b'\r\n')
buf = (
(b'--%s\r\n' % boundary_bytes) +
(b'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' %
(filename_bytes, filename_bytes)) +
(b'Content-Type: %s\r\n' % mtype.encode()) +
b'\r\n'
)
yield write(buf)
with open(filename, 'rb') as f:
while True:
# 16k at a time.
@ -95,7 +97,6 @@ def put(filenames):
method='PUT',
headers=headers,
body_producer=producer)
print(response)