Python:HTTP通过流发布大文件
发布于 2021-01-29 16:14:13
我正在将可能较大的文件上传到Web服务器。目前,我正在这样做:
import urllib2
f = open('somelargefile.zip','rb')
request = urllib2.Request(url,f.read())
request.add_header("Content-Type", "application/zip")
response = urllib2.urlopen(request)
但是,这会在发布文件之前将整个文件的内容读取到内存中。如何将文件流传输到服务器?
关注者
0
被浏览
50
1 个回答
-
通过阅读由systempuntoout链接到的邮件列表线程,我找到了解决方案的线索。
该
mmap
模块允许您打开充当字符串的文件。文件的某些部分将按需加载到内存中。这是我现在使用的代码:
import urllib2 import mmap # Open the file as a memory mapped string. Looks like a string, but # actually accesses the file behind the scenes. f = open('somelargefile.zip','rb') mmapped_file_as_string = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) # Do the request request = urllib2.Request(url, mmapped_file_as_string) request.add_header("Content-Type", "application/zip") response = urllib2.urlopen(request) #close everything mmapped_file_as_string.close() f.close()