Подключение к Google calendar api на python
Не могу настроить доступ к API календаря Google с помощью python с сервера unix.
Пробовал использовать этот маунуал https://developers.google.com/calendar/api/quickstart/python. На данный момент я запускаю quickstart.py и получаю в консоли
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=99236485634896-kkavoaib8mp8ert4eri2d5v6gicfln14i0k.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A42403%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar&state=XEqxqNSDNKfksdfgwUXw24JjK4EzA4G&access_type=offline
Traceback (most recent call last):
File "/home/calendar/quickstart.py", line 63, in <module>
main()
File "/home/calendar/quickstart.py", line 33, in main
creds = flow.run_local_server(port=0)
File "/home/calendar/.local/lib/python3.10/site-packages/google_auth_oauthlib/flow.py", line 446, in run_local_server
authorization_response = wsgi_app.last_request_uri.replace("http", "https")
AttributeError: 'NoneType' object has no attribute 'replace'
При переходе по ссылке я вижу экран авторизации Google, выбираю аккаунт, разрешаю доступ, после чего меня перенаправляет на ссылку http://localhost:42403/?state=XEkxqN2KMDSgXknqUXw24JjK4EzA4G&code=4/2AbUR2VOHwy3nuCXdumqaJejyAb8F0N7LXQ2JA48EGgtuzCm64 uNc YJRb7wfTLgnVSA1C8g&scope=https://www.googleapis.com/auth/calendar и я вижу в браузере "Не удается получить доступ к сайту".
quickstart.py:
from __future__ import print_function
import datetime
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar']
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.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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(
'client_secret_99236485634896-mlsfkvkldfmldfer34o3fiodfficfln14i0k.apps.googleusercontent.com.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
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.')
return
# Prints the start and name of the next 10 events
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
except HttpError as error:
print('An error occurred: %s' % error)
if __name__ == '__main__':
main()
Помогите разобраться - что не так и как поправить чтобы подключиться к апи?
Источник: Stack Overflow на русском