欢迎访问宙启技术站
智能推送

在Python中通过from_client_config()函数生成GoogleAuthOAuthLibInstalledAppFlow,并附带完整代码示例

发布时间:2024-01-04 18:54:46

在Python中使用Google的OAuth 2.0库来生成Google Auth OAuthLib InstalledAppFlow,需要先创建一个Google Cloud Platform(GCP)项目,并启用所需的API和服务。下面是一个完整的代码示例,包括使用例子:

import os
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

# 定义要访问的Google API的范围
SCOPES = ['https://www.googleapis.com/auth/calendar']

# 定义客户端配置文件路径
CLIENT_CONFIG_PATH = 'client_secret.json'

def get_credentials():
    # 如果之前已经运行过授权流,可以读取已保存的凭证
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        return creds

    # 使用Google的from_client_config函数生成InstalledAppFlow对象
    flow = InstalledAppFlow.from_client_config(
        client_config_file=CLIENT_CONFIG_PATH,
        scopes=SCOPES
    )

    # 开始用户授权流程
    creds = flow.run_local_server(port=0)

    # 保存凭证
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

    return creds

# 获取凭证
credentials = get_credentials()

# 使用凭证进行API调用,这里以Google Calendar API为例
from googleapiclient.discovery import build

# 创建API服务对象
service = build('calendar', 'v3', credentials=credentials)

# 获取当前用户的日历列表
calendar_list = service.calendarList().list().execute()

# 打印日历列表
for calendar in calendar_list['items']:
    print(calendar['summary'])

在上面的示例中,我们首先导入了CredentialsInstalledAppFlow类。Credentials类用于管理Google API的凭证,InstalledAppFlow类用于生成用于本地应用程序的授权流。

我们首先定义了要访问的Google API的范围,在这个示例中,我们使用了Google日历API的只读访问范围。

然后,我们指定了存储Google客户端配置文件的路径,该文件应该是您在Google Cloud Platform上创建项目时生成的JSON文件。

get_credentials函数首先检查是否已经存在之前保存下来的凭证文件token.json。如果已经存在,它会加载凭证并返回。否则,它将使用from_client_config函数生成InstalledAppFlow对象,并开始用户授权流程。用户将在浏览器中收到一个授权页面,用于选择要授权给该应用程序的Google账户。一旦用户确认授权,授权流程将自动将凭证保存到token.json文件中,并返回凭证。

获取凭证之后,我们可以使用它来构建API服务对象。在本例中,我们使用build函数创建了一个Calendar API的服务对象。

最后,我们可以使用API服务对象来调用Google Calendar API的相应方法。在这个例子中,我们调用了calendarList().list()方法来获取当前用户的日历列表,并打印日历列表中的每个日历的summary属性。

运行这个示例代码时, 次会出现一个浏览器窗口,请求用户登录并授权应用程序。用户完成授权后,将生成token.json文件来保存凭证。在之后的运行会自动加载token.json文件,无需再次进行授权。

希望这个示例能帮助你使用Google OAuth 2.0来生成Google Auth OAuthLib InstalledAppFlow,并进行相应的API调用。