簡體   English   中英

Google 日歷 API 使用入門

[英]Google calender API getting started

我正在嘗試熟悉谷歌日歷 api。 在入門指南中,他們有這個代碼示例:

from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']


def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        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()

在這個例子中,如果我們還沒有通過 pickle 文件進行訪問,我們會自動打開一個窗口,要求用戶訪問他們的日歷。 問題是我不希望這個窗口自動打開,我想打印一個鏈接,而不是用戶可以單擊以進行身份​​驗證。 我在文檔中環顧四周,但似乎找不到任何有用的東西。 我會感謝我能得到的任何幫助,謝謝!

  • 對於授權過程,您只想顯示 URL。 您不想自動打開瀏覽器。
  • 您想使用 googleapis 和 python 來實現這一點。

如果我的理解是正確的,這個答案怎么樣? 請將此視為幾種可能的答案之一。

在這種情況下,請使用Flow.from_client_secrets_file而不是InstalledAppFlow.from_client_secrets_file

修改后的腳本:

當您的腳本被修改時,請進行如下修改。

從:

from google_auth_oauthlib.flow import InstalledAppFlow

到:

from google_auth_oauthlib.flow import Flow

從:

if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

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

到:

if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        # Create the flow using the client secrets file from the Google API
        # Console.
        flow = Flow.from_client_secrets_file('client_secret.json', SCOPES, redirect_uri='urn:ietf:wg:oauth:2.0:oob')

        # Tell the user to go to the authorization URL.
        auth_url, _ = flow.authorization_url(prompt='consent')

        print('Please go to this URL: {}'.format(auth_url))

        # The user will get an authorization code. This code is used to get the
        # access token.
        code = input('Enter the authorization code: ')
        flow.fetch_token(code=code)
        creds = flow.credentials

    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('calendar', 'v3', credentials=creds)
  • 在這種情況下,當您在token.pickle is not existing 下運行腳本時,授權的 URL 將顯示到控制台。 瀏覽器沒有打開。 因此,請通過打開瀏覽器訪問 URL 並授權范圍。 然后,請將復制的授權碼發送到控制台並輸入回車鍵。 通過這種方式,檢索訪問令牌並創建token.pickle文件。

筆記:

  • 如果出現重定向uri相關的錯誤,請將其修改為http://localhost並再次測試。

參考:

如果我誤解了您的問題並且這不是您想要的方向,我深表歉意。

添加:

  • I want to print a link instead that the user can click to authenticate在您的問題中I want to print a link instead that the user can click to authenticate ,我提出了上面的示例腳本。
  • some way not to manually confirm authorization codes在您的回復中some way not to manually confirm authorization codes ,我認為上面的示例腳本不合適。

在這種情況下,如何使用服務帳戶? 使用服務帳號時,不需要授權碼。 使用服務帳號的腳本如下。

示例腳本:

from google.oauth2 import service_account
from googleapiclient.discovery import build

SERVICE_ACCOUNT_FILE = 'service-account-credentials.json'  # Here, please set the creadential file of the service account.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)

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

筆記:

  • 為了使用服務帳號訪問谷歌日歷,首先請將谷歌日歷與服務帳號的郵箱共享。 請注意這一點。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM