def multipart_encode(vars, files, boundary = None, buf = None):
if boundary is None:
boundary = mimetools.choose_boundary()
if buf is None:
buf = ''
for (key, value) in vars:
if key is not None and value is not None:
buf += '--%s\r\n' % boundary
buf += 'Content-Disposition: form-data; name="%s"' % key
buf += '\r\n\r\n' + value + '\r\n'
for (key, fd) in files:
file_size = os.fstat(fd.fileno())[stat.ST_SIZE] if isinstance(fd, file) else fd.len
filename = fd.name.split('/')[-1] if '/' in fd.name else fd.name.split('\\')[-1]
try:
contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
except:
# Reference: http://bugs.python.org/issue9291
contenttype = 'application/octet-stream'
buf += '--%s\r\n' % boundary
buf += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
buf += 'Content-Type: %s\r\n' % contenttype
# buf += 'Content-Length: %s\r\n' % file_size
fd.seek(0)
buf = str(buf)
buf += '\r\n%s\r\n' % fd.read()
buf += '--%s--\r\n\r\n' % boundary
return boundary, buf
评论列表
文章目录