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

使用Python编写flow_from_clientsecrets()授权流程的完整代码

发布时间:2023-12-11 15:47:46

使用Python编写flow_from_clientsecrets()授权流程的完整代码如下:

from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow


def authorize_client_secrets(client_secrets_path, scopes):
    # Create a flow using the client secrets file
    flow = flow_from_clientsecrets(client_secrets_path, scopes=scopes)

    # Try to retrieve credentials from the storage
    storage = Storage('credentials.dat')
    credentials = storage.get()

    # If the credentials don't exist or are invalid, run the flow to authorize the client
    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage)

    return credentials


def main():
    # Define the client secrets file path and the desired scopes
    client_secrets_path = 'client_secrets.json'
    scopes = ['https://www.googleapis.com/auth/calendar']

    # Authorize the client using the client secrets file and scopes
    credentials = authorize_client_secrets(client_secrets_path, scopes)

    # Use the authorized credentials to make API requests
    # For example, using the Google Calendar API
    from googleapiclient.discovery import build

    service = build('calendar', 'v3', credentials=credentials)
    events_result = service.events().list(calendarId='primary', maxResults=10, singleEvents=True,
                                          orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])


if __name__ == '__main__':
    main()

使用例子:

1. 准备工作:

- 安装必要的Python库:oauth2clientgoogle-api-python-client

- 从Google Cloud Console创建OAuth客户端凭据并下载其JSON文件,例如client_secrets.json

- 保存代码并准备一个空的文件夹以保存授权凭据

2. 编辑client_secrets.json文件,将其路径添加到代码的相应部分。

3. 运行代码,首次运行程序将打开浏览器以授权您的应用程序访问Google API。按照提示操作,然后复制授权码。

4. 返回Python控制台,并将授权码粘贴到提示符中。

5. 授权成功后,您的应用程序将具有对Google API的访问权限,并显示您的Google日历的前10个事件的时间和概要信息。