首页 > 解决方案 > 从 django-python 访问 Google 驱动器

问题描述

Django我使用社交身份验证应用程序实现社交登录时,我按照此链接进行配置。 Goolge OAuth工作良好;google-oauth2访问令牌存储在额外的数据字段中。

现在我想使用这个访问令牌列出谷歌驱动器文件。我试过这个。

def drive(request):
    user = request.user
    social = user.social_auth.get(provider='google-oauth2')
    response = requests.get(
        'https://www.googleapis.com/auth/drive.metadata.readonly',
        params={'access_token': social.extra_data['access_token']})
    print(response)
    return render(request, 'home/drive.html', {'checking':response})

我收到了200回复,但我不知道如何列出文件。

我正在使用django 2.0.3python 3.5

标签: pythondjangogoogle-oauth

解决方案


将设置更改为重新提示 Google OAuth2 用户刷新 refresh_token

SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type':'离线'}

并使用 google-auth 库对 Google API 进行身份验证

def drive(request):
    user = request.user
    social = user.social_auth.get(provider='google-oauth2')
    creds=google.oauth2.credentials.Credentials(social.extra_data['access_token'])
    drive = googleapiclient.discovery.build('drive', 'v3', credentials=creds)
    files = drive.files().list().execute()

参考:

  1. https://developers.google.com/api-client-library/python/auth/web-app
  2. https://google-auth.readthedocs.io/en/latest/user-guide.html
  3. https://python-social-auth-docs.readthedocs.io/en/latest/use_cases.html

推荐阅读