Google Drive在python中读取部分文件

时间:2012-09-01 17:00:11

标签: google-app-engine google-drive-api

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

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实际上是文件metadata中的'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

1 个答案:

答案 0 :(得分:1)

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