首页 > 解决方案 > 从身份验证代码在 token.pickle 中创建和存储 Google 凭据

问题描述

我正在编写一个程序,它使用本地token.pickle文件来访问用户的谷歌日历。

它在服务器上运行,我希望用户能够通过 Web 界面登录,然后服务器创建并存储 token.pickle 文件,该文件是根据页面发送回服务器的身份验证代码创建的。

我现在的位置是我的 Python 后端接收到授权代码,但我不知道如何从中创建 token.pickle 文件......我知道我需要交换用户凭据的代码,我可能需要使用以下代码段:

with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

# Set path to the Web application client_secret_*.json file you downloaded from the
# Google API Console: https://console.developers.google.com/apis/credentials
CLIENT_SECRET_FILE = '/path/to/client_secret.json'

# Exchange auth code for access token, refresh token, and ID token
credentials = client.credentials_from_clientsecrets_and_code(
    CLIENT_SECRET_FILE,
    ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
    auth_code)

谢谢,我将不胜感激任何帮助。

编辑:

好的,所以我想保存某种从访问令牌中获取凭据或凭据本身的方法,这样我就可以从以下位置访问它们:

service = build('calendar', 'v3', credentials=creds)

有人可以澄清或给我一个方法吗?

标签: python-3.xgoogle-apigoogle-oauthgoogle-calendar-apigoogle-api-python-client

解决方案


推荐阅读