在谷歌驱动器上传的python代码......
链接: http://wescpy.blogspot.in/2015/12/google-drive-uploading-downloading.html
代码:
#!/usr/bin/env python
from __future__ import print_function
import os
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store, flags) \
if flags else tools.run(flow, store)
DRIVE = build('drive', 'v2', http=creds.authorize(Http()))
FILES = (
('ex.xls', False),
('ex.xls', True),
)
for filename, convert in FILES:
metadata = {'title': filename}
res = DRIVE.files().insert(convert=convert, body=metadata,
media_body=filename, fields='mimeType,exportLinks').execute()
if res:
print('Uploaded1: "%s" (%s)' % (filename, res['mimeType']))
if res:
MIMETYPE = 'application/pdf'
res, data = DRIVE._http.request(res['exportLinks'][MIMETYPE])
if data:
fn = '%s.pdf' % os.path.splitext(filename)[0]
with open(fn, 'wb') as fh:
fh.write(data)
print('Downloaded "%s" (%s)' % (fn, MIMETYPE))
错误:
Uploaded1: "ex.xls" (application/vnd.ms-excel)
Traceback (most recent call last):
File "wescpy.py", line 32, in <module>
media_body=filename, fields='mimeType,exportLinks').execute()
File "/home/optimus/anaconda3/lib/python3.6/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/optimus/anaconda3/lib/python3.6/site-packages/googleapiclient/http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 500 when requesting https://www.googleapis.com/upload/drive/v2/files?convert=true&fields=mimeType%2CexportLinks&alt=json&uploadType=multipart returned "">
文档(https://developers.google.com/drive/v2/web/handle-errors)
建议:使用指数退避,在重试非幂等请求之前包括检查。
store = file.Storage('storage.json')