如何使用谷歌.auth而不是Python中的oauth2client来访问我的googlecalend

2024-09-20 05:44:15 发布

您现在位置:Python中文网/ 问答频道 /正文

几年前,我创建了一个小Python程序,该程序能够使用oauth2client维护我的日历,而oauth2client现在已被弃用,取而代之的是谷歌.auth-但是我找不到任何有用的文档,我的程序停止工作,抱怨一个_modulekeyerror,除了升级,似乎没有人能解决这个问题。在

我不知道如何将oauth2client替换为谷歌.auth公司名称:

import datetime
import httplib2
import os

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

。。。在

^{pr2}$

Tags: from文档import程序名称authdatetimeos
2条回答

根据oauth2client deprecation notes,用于管理Google用户凭证的替换项是google-auth-oauthlib。下面是在我的电脑上工作的代码片段(python3.6)。在

由于文档强调新库没有保存凭证,所以我使用pickle保存凭证。也许,根据您的应用程序需求,您希望有一个更健壮的解决方案(比如数据库)。在

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)

我还没有对此进行过可靠的测试,但它可以用我的个人帐户测试代码片段。我确信对于企业应用程序,可以和/或应该对其进行更改,例如传递auth'dHttp()实例,检测范围更改,等等。在

您可以查看my GitHub repo上的完整代码:

要求:

  • googleapi python客户端
  • 谷歌认证
  • 谷歌认证oauthlib
  • 不管上面提到什么

我使用^{}类,通常遵循Google's Python auth guide上的说明。在

代码(Python3.6)

# Google API imports
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['your scopes', 'here']

def get_saved_credentials(filename='creds.json'):
    '''Read in any saved OAuth data/tokens
    '''
    fileData = {}
    try:
        with open(filename, 'r') as file:
            fileData: dict = json.load(file)
    except FileNotFoundError:
        return None
    if fileData and 'refresh_token' in fileData and 'client_id' in fileData and 'client_secret' in fileData:
        return Credentials(**fileData)
    return None

def store_creds(credentials, filename='creds.json'):
    if not isinstance(credentials, Credentials):
        return
    fileData = {'refresh_token': credentials.refresh_token,
                'token': credentials.token,
                'client_id': credentials.client_id,
                'client_secret': credentials.client_secret,
                'token_uri': credentials.token_uri}
    with open(filename, 'w') as file:
        json.dump(fileData, file)
    print(f'Credentials serialized to {filename}.')

def get_credentials_via_oauth(filename='client_secret.json', scopes=SCOPES, saveData=True) -> Credentials:
    '''Use data in the given filename to get oauth data
    '''
    iaflow: InstalledAppFlow = InstalledAppFlow.from_client_secrets_file(filename, scopes)
    iaflow.run_local_server()
    if saveData:
        store_creds(iaflow.credentials)
    return iaflow.credentials

def get_service(credentials, service='sheets', version='v4'):
    return build(service, version, credentials=credentials)

那么用法是:

^{pr2}$

相关问题 更多 >