AccessOokenRefreshError:来自oauth2client的invalid_grant

Vis*_*ant 5 python google-api-python-client

我正在创建一个脚本,使用Google-api-python-client为特定的Google Apps用户下载文件.首先,我试图获取用户帐户包含的文件列表.我按照链接https://developers.google.com/drive/v2/reference/files/list中给出的示例进行操作

代码块如下

用户对客户的授权

def authorize_application(request):

    #setting flow to get permission and code 
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI, ACCESS_TYPE)
    authorize_url = flow.step1_get_authorize_url()

    code = request.GET.get('code', '')

    if code:
        #import ipdb
        #ipdb.set_trace()
    #setting flow step2 to exchage code for access token    
        credential = flow.step2_exchange(code)

    #initialising httplib2 instance and building a DriveAPI service
        http = httplib2.Http()
        http = credential.authorize(http)
        drive_service = build('drive', 'v2', http=http)

        # getting user's data
    about = drive_service.about().get().execute()
        user_info = about.get('user')
        email = user_info.get('emailAddress')
        request.session['username'] = email[0:email.index('@')]
        username = request.session['username']
        #import ipdb
        #ipdb.set_trace()
        #creating a Django user object 
    user, created = User.objects.get_or_create(username=username, email=email)

    #saving credentials to database 
        if created == True: 
            storage = Storage(CredentialsModel, 'id', user, 'credential')
            storage.put(credential)
            return HttpResponseRedirect('/download/')
        else:
        return HttpResponseRedirect('/download/')
    else:
        return HttpResponseRedirect(authorize_url)
Run Code Online (Sandbox Code Playgroud)

获取用户Drive中的文件列表

def download_file(request):

    #import ipdb
    #ipdb.set_trace()

    username = request.session['username']
    user = User.objects.get(username=username)

    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()

    access_token = credential.access_token

    http = httplib2.Http()
    http = credential.authorize(http)
    drive_service = build('drive', 'v2', http=http)

    result = []
    page_token = access_token

    while True:

    try:
        param = {}
            if page_token:
                param['pageToken'] = page_token
            files = drive_service.files().list(**param).execute()

            result.extend(files['items'])
                page_token = files.get('nextPageToken')

        if not page_token:
        break
    except errors.HttpError, error:
        print 'An error occured: %s' % error
        break

    return HttpResponse(result)
Run Code Online (Sandbox Code Playgroud)

它正在保存并从数据库中检索凭证,但它在files = drive_service.files()时给出错误"AccessTokenRefreshError:invalid_grant".list(**param).execute()of download_file()

我做错了什么?请建议正确的方法.

wes*_*cpy 1

(2017 年 2 月)不确定您的问题是什么,但有几件事:1) Drive API 有更新的版本(v3),2) 您使用的身份验证代码现在可以通过最近的更新显着简化Google API 客户端库。(确保使用pip install -U google-api-python-client[或pip3适用于 Python 3] 更新 Python 库。)

下面是一个可行的解决方案 - 告诉我它是否适合您 - 我在这篇博文这个视频中写下了它。我省略了about()获取用户信息的调用,但我将代码分为与上面相同的两个部分,但如您所见,代码少得多:

用户对客户端的授权

SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
    creds = tools.run_flow(flow, store)
Run Code Online (Sandbox Code Playgroud)

获取用户云端硬盘中的文件列表(前 100 个文件)

DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
files = DRIVE.files().list().execute().get('files', [])
for f in files:
    print(f['name'], f['mimeType'])
Run Code Online (Sandbox Code Playgroud)

如果您想了解有关使用 Drive API 的更多信息,以下是我创建的一些其他资源(视频、博客文章等):

(*) - TL;DR:将纯文本文件上传到云端硬盘,导入/转换为 Google 文档格式,然后将该文档导出为 PDF。上面的帖子使用 Drive API v2,就像您的代码示例一样;这篇后续文章描述了将其迁移到 Drive API v3,这里有一个开发人员视频,结合了“穷人的转换器”帖子。