Начало работы с Google Calender API - PullRequest
0 голосов
/ 13 марта 2020

Я пытаюсь ознакомиться с API календаря Google. В руководстве по началу работы они имеют следующий пример кода:

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. Дело в том, что я не хочу, чтобы это окно открывалось автоматически, я хочу напечатать ссылку, которую пользователь может щелкнуть для аутентификации. Я посмотрел в документации, но не могу найти ничего полезного. Я бы хотел получить любую помощь, спасибо!

1 Ответ

1 голос
/ 13 марта 2020
  • Для процесса авторизации вы хотите показать только 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 не существует, URL для авторизации отображается на консоли. Браузер не открывается. Поэтому, пожалуйста, получите доступ к URL, открыв браузер и авторизовав области. Затем скопируйте код авторизации в консоль и введите клавишу ввода. Таким образом извлекается токен доступа и создается файл token.pickle.

Примечание:

  • Если возникает ошибка, связанная с URI перенаправления, измените http://localhost и протестировать снова.

Ссылка:

Если Я неправильно понял ваш вопрос, и это было не то направление, которое вы хотите, извиняюсь.

Добавлено:

  • С I want to print a link instead that the user can click to authenticate в вашем вопросе я предложил приведенный выше пример сценария.
  • Начиная с 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)

Примечание:

  • Для доступа к календарю Google с помощью Сервисная учетная запись, сначала, пожалуйста, поделитесь календарем Google с адресом электронной почты сервисной учетной записи. Пожалуйста, будьте осторожны.

Ссылка:

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...