Chris Atlee's poster library works really well for this (particularly the convenience function poster.encode.multipart_encode()
). As a bonus, it supports streaming of large files without loading an entire file into memory. See also Python issue 3244.