Python - 使用谷歌驱动API时的HttpError

时间:2015-04-26 20:53:29

标签: python-3.x google-api

我正在使用python 3.4来利用Google API访问和读取用户google驱动器中的文件。如果用户在应该拥有凭据文件之前已经使用过该应用程序,那么我希望能够通过尝试列出用户驱动器上的文件来测试凭据是否仍然有效。这个想法是,如果这个错误然后应用程序知道它需要再次请求访问。

经过大量搜索后,我尝试将以下示例中的代码拼凑起来:
Google API commands
Google Example

我目前有以下代码:

import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow

def getAccess():
    flow = OAuth2WebServerFlow(client_id, client_secret, scope,     redirect_uri="urn:ietf:wg:oauth:2.0:oob")
    auth_uri = flow.step1_get_authorize_url()
    print("Please go to the following webpage and copy and paste the access key onto the command line:\n" + auth_uri + "\n")
    code = input("Please enter your access code:\n")
    credentials = flow.step2_exchange(code)
    storage.put(credentials)

client_id = MYCLIENT_ID
client_secret = MYCLIENT_SECRET
scope = "https://www.googleapis.com/auth/drive"

storage = Storage('~/credentials.dat')
credentials = storage.get()

if credentials is None or credentials.invalid:
    getAccess()
else:
    try:
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build('drive', 'v2', http=http)
        param = {}
        service.files().list(**param).execute()
    except:
        getAccess()

但是service.files()。list(** param).execute()行会产生以下错误消息:

Traceback (most recent call last):
  File "GoogleAuth.py", line 64, in <module>
    service.files().list(**param).execute()
  File "C:\Anaconda3\lib\site-packages\oauth2client\util.py", line 137, in     positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Anaconda3\lib\site-packages\googleapiclient\http.py", line 729, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError

我尝试过几种不同的组合,例如:

service.files().list().execute()
service.apps().list().execute()

但是我仍然收到相同的错误消息。知道发生了什么吗?

1 个答案:

答案 0 :(得分:1)

问题是那个

    service = build('drive', 'v2')

应该是

    service = build('drive', 'v2', http=http)