簡體   English   中英

如何使用httplib2下載大文件

[英]How to download a large file with httplib2

是否可以使用httplib2批量下載大文件。 我正在從Google API下載文件,並且為了使用來自Google OAuth2WebServerFlow的憑據,我必須使用httplib2。

目前,我正在執行以下操作:

flow = OAuth2WebServerFlow(
    client_id=XXXX,
    client_secret=XXXX,
    scope=XYZ,
    redirect_uri=XYZ
)

credentials = flow.step2_exchange(oauth_code)

http = httplib2.Http()
http = credentials.authorize(http)

resp, content = self.http.request(url, "GET")
with open(file_name, 'wb') as fw:
    fw.write(content)

但是content變量可以獲得超過500MB。

有什么辦法可以分塊讀取響應嗎?

您可以考慮Streaming_httplib2 ,它是httplib2的一個分支,具有確切的行為變化。

為了使用來自Google OAuth2WebServerFlow的憑據,我必須使用httplib2。

如果您需要httplib2中不提供的功能,則值得研究如何使憑證處理與另一個HTTP庫一起使用將花費多少。 這可能是一項不錯的長期投資。 (例如, 如何使用request.py在python中下載大文件?

關於分塊讀取響應(與httplib一起使用,必須與httplib2一起使用)

import httplib
conn = httplib.HTTPConnection("google.com")
conn.request("GET", "/")
r1 = conn.getresponse()

try:
    print r1.fp.next()
    print r1.fp.next()
except:
    print "Exception handled!"

注意: next()可能會引發StopIteration異常,您需要對其進行處理。

您可以避免像這樣調用next()

F=open("file.html","w")
for n in r1.fp:
    F.write(n)
    F.flush()

您可以將oauth2client.client.Credentials應用於urllib2請求。

首先,獲取credentials對象。 就您而言,您正在使用:

credentials = flow.step2_exchange(oauth_code)

現在,使用該對象獲取auth標頭,並將其添加到urllib2請求中:

req = urllib2.Request(url)
auth_headers = {}
credentials.apply(auth_headers)
for k,v in auth_headers.iteritems():
  req.add_header(k,v)
resp = urllib2.urlopen(req)

現在resp是一個類似於文件的對象,您可以使用它來讀取URL的內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM