2

我有一个 App Engine 站点,我想从 Google Drive 中的文件中获取最后 300 个字节。我尝试将 HTTP Range 标头与 Python 的 urllib2 一起使用,如下所示:

req = urllib2.Request(url)
req.headers['Range'] = 'bytes=%s-%s' % (-300, 2)
f = urllib2.urlopen(req)
# This shows you the *actual* bytes that have been downloaded.
range=f.headers.get('Content-Range')
logging.info("range:"+range)
logging.info("read:"+(f.read()))

url 实际上是文件元数据中的“downloadurl”属性。运行它时出现此错误

  File "C:\Python27\lib\urllib2.py", line 527, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 401: Unauthorized

是否可能不接受 Range 标头?我真的不想下载整个文件。有解决方案的人吗?

编辑

感谢@Claudio Cherubino 的回答!

creds = GetSessionCredentials() //from Google Python Client API
size = int('size of my file')
headers = {"Range" : 'bytes=%s-%s' % (size-300, size)} //Range Header
http = httplib2.Http()
http = creds.authorize(http) //add OAuth credentials
resp, content = http.request(url, "GET", body=None, headers=headers)
if resp.status == 206:
   print 'Status: %s' % resp
   print "content:"+content
else:
    print 'An error occurred: %s' % resp
4

1 回答 1

1

您必须按照文档中的说明向您的请求添加 OAuth 令牌:https ://developers.google.com/drive/credentials

于 2012-09-01T18:32:13.680 回答