如何在 Python 中使用 google.auth 而不是 oauth2client 来访问我的 Google 日历 [英] How do I use google.auth instead of oauth2client in Python to get access to my Google Calendar

查看:52
本文介绍了如何在 Python 中使用 google.auth 而不是 oauth2client 来访问我的 Google 日历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几年前,我创建了一个小型 Python 程序,该程序能够使用 oauth2client 维护我的日历,现在已弃用并替换为 google.auth - 但我找不到任何有用的文档,我的程序停止工作,抱怨 _module KeyError除了升级,似乎没有人能解决.

Several years ago I created a small Python program which were able to maintain my calendar using oauth2client which is now deprecated and replaced with google.auth - but I cannot find any useful documentation and my program stopped working complaining about a _module KeyError which nobody appear to have solved except by upgrading.

我不知道如何用 google.auth 替换 oauth2client:

I cannot figure out how to replace the oauth2client with google.auth:

import datetime
import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

...

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)

推荐答案

根据 oauth2client 弃用说明,用于管理 Google 用户凭据的替代品是 google-auth-oauthlib.下面是在我的 PC 上运行的代码片段(python 3.6).

According to the oauth2client deprecation notes, the replacement to be used to manage Google user credentials is google-auth-oauthlib. Below a snippet working on my PC (python 3.6).

由于文档强调新库不保存凭据,这就是为什么我使用 pickle 来保存它们.也许,根据您的应用程序要求,您想要一个更强大的解决方案(如数据库).

As the documentation highlights the new library does not save the credentials, that's why I am using pickle to save them. Maybe, depending on your application requirements, you want to have a more robust solution (like a database).

import os
import pickle

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/calendar.readonly', ]


# we check if the file to store the credentials exists
if not os.path.exists('credentials.dat'):

    flow = InstalledAppFlow.from_client_secrets_file('client_id.json', SCOPES)
    credentials = flow.run_local_server()

    with open('credentials.dat', 'wb') as credentials_dat:
        pickle.dump(credentials, credentials_dat)
else:
    with open('credentials.dat', 'rb') as credentials_dat:
        credentials = pickle.load(credentials_dat)

if credentials.expired:
    credentials.refresh(Request())

calendar_sdk = build('calendar', 'v3', credentials=credentials)

calendars_get_params = {
        'calendarId': 'primary',
    }

test = calendar_sdk.calendars().get(**calendars_get_params).execute()
print(test)

这篇关于如何在 Python 中使用 google.auth 而不是 oauth2client 来访问我的 Google 日历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆