尝试在 Google Colab 上调用 Google Calendar API(使用 gcsa),但凭据路径不正确

问题描述 投票:0回答:3

我正在编写一个调用 Google 日历 API 的 Python 脚本,以便我可以在我的 Google 日历中创建一个事件。使用官方文档设置日历 API 是一场噩梦,所以我使用 gcsa(Google Calendar Simple API)。我在 Colab 上安装了 Google Drive 中的事件创建脚本。然而,找不到

credentials.json

我用过:

gc = GoogleCalendar(credentials_path='content/drive/MyDrive/Colab Notebooks/credentials.json')

指定我从 Google Workspace 下载的

credentials.json
文件的路径。
root/.credentials/
的默认路径在 Google Colab 中不起作用(但在我的笔记本电脑上有效)。这些是我收到的错误消息。我该怎么办?

   gc = GoogleCalendar(credentials_path='content/drive/MyDrive/Colab Notebooks/credentials.json')
  File "/usr/local/lib/python3.8/dist-packages/gcsa/google_calendar.py", line 62, in __init__
    super().__init__(
  File "/usr/local/lib/python3.8/dist-packages/gcsa/_services/base_service.py", line 18, in __init__
    super().__init__(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/gcsa/_services/authentication.py", line 60, in __init__
    self.credentials = self._get_credentials(
  File "/usr/local/lib/python3.8/dist-packages/gcsa/_services/authentication.py", line 101, in _get_credentials
    flow = InstalledAppFlow.from_client_secrets_file(credentials_path, scopes)
  File "/usr/local/lib/python3.8/dist-packages/google_auth_oauthlib/flow.py", line 204, in from_client_secrets_file
    with open(client_secrets_file, "r") as json_file:
FileNotFoundError: [Errno 2] No such file or directory: 'content/drive/MyDrive/Colab Notebooks/credentials.json'
python google-colaboratory google-calendar-api gcsa
3个回答
0
投票

我成功了!从 Token 对象的 gcsa 文档中,我使用了:

from google.oauth2.credentials import Credentials 

token = Credentials(
token='<access_token>',
refresh_token='<refresh_token>',
client_id='<client_id>',
client_secret='<client_secret>',
scopes=['googleapis.com/auth/calendar'],
token_uri='oauth2.googleapis.com/token'
)
gc = GoogleCalendar(credentials=token)

我从在笔记本电脑上运行代码时生成的 token.json 中获取了参数。我很高兴它现在有效了! :)

但是这是正确的方法吗?在我必须获得新的令牌之前,该令牌能持续多久?


0
投票

我认为你的问题只是文件路径。如果您的驱动器已安装,您应该能够使用

'content'

中的相对路径
gc = GoogleCalendar(credentials_path='drive/MyDrive/Colab Notebooks/credentials.json') # without content/

或绝对路径:

gc = GoogleCalendar(credentials_path='/content/drive/MyDrive/Colab Notebooks/credentials.json') # with / at the start

至于“令牌能持续多久,直到我必须获得新的?”,您可能会遇到这个问题


顺便说一句,我是该库的作者,如果您觉得文档可能需要一些说明,请与我们联系。


0
投票

从目录中删除内容。它将正常运行。

© www.soinside.com 2019 - 2024. All rights reserved.