Các tài liệu không nói rằng bạn có thể làm điều này, nhưng mã trong urllib2 (và httplib) chấp nhận bất kỳ đối tượng với một phương pháp read() như dữ liệu. Vì vậy, bằng cách sử dụng một tập tin mở dường như làm các trick.
Bạn sẽ cần tự đặt tiêu đề Độ dài nội dung. Nếu nó không được thiết lập, urllib2 sẽ gọi len() trên dữ liệu, các đối tượng tệp nào không hỗ trợ.
import os.path
import urllib2
data = open(filename, 'r')
headers = { 'Content-Length' : os.path.getsize(filename) }
response = urllib2.urlopen(url, data, headers)
Đây là mã có liên quan xử lý dữ liệu bạn cung cấp. Đó là từ lớp HTTPConnection
trong httplib.py
bằng Python 2.7:
def send(self, data):
"""Send `data' to the server."""
if self.sock is None:
if self.auto_open:
self.connect()
else:
raise NotConnected()
if self.debuglevel > 0:
print "send:", repr(data)
blocksize = 8192
if hasattr(data,'read') and not isinstance(data, array):
if self.debuglevel > 0: print "sendIng a read()able"
datablock = data.read(blocksize)
while datablock:
self.sock.sendall(datablock)
datablock = data.read(blocksize)
else:
self.sock.sendall(data)
Nguồn
2015-06-12 19:16:16
liên quan: [file WSGI streaming với một máy phát điện] (http : //stackoverflow.com/questions/11811404/) –
Related: http://stackoverflow.com/questions/2502596/python-http-post-a-large-file-with-streaming –