使用Python访问Google日历API

2 投票
1 回答
2286 浏览
提问于 2025-04-17 16:37

我现在正在开发一个简单的Python应用程序,用来和我的Google日历互动。为了实现这个功能,我第一次使用Google日历的API,借助Google提供的Python库。

不过,尽管有文档指导,我在往日历里插入新事件时遇到了瓶颈。下面是我用来连接和执行请求的代码片段:

import sys
...
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

...

flow = flow_from_clientsecrets('client_secrets.json',
    scope='https://www.googleapis.com/auth/calendar',
    redirect_uri='http://localhost')

storage = Storage('credentials.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
  credentials = run(flow, storage)

http = httplib2.Http()
http = credentials.authorize(http)
service = build('calendar', 'v3', http=http)

try:
  event = {
    "start": "2013-02-20T09:00:00.000+01:00",
    "end": "2013-02-20T11:00:00.000+01:00",
    "summary": "New event",
    "location": "Paris, FRANCE"
  }
  service.events().insert(calendarId='primary', body=event).execute()
  print "END"
except AccessTokenRefreshError:
  print ('Credentials have been revoked')

执行后,我得到了这样的结果:

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

到目前为止,我尝试了很多方法,包括在Google日历API的参考文档中找到的所有代码示例,但情况没有任何改变。

提前感谢你的帮助。

1 个回答

0

我遇到了和你几乎一模一样的问题。试着在你的 client_secrets.json 文件里加上这一行:
"access_type":"offline"

这样做可以确保你能拿到一个刷新令牌,而不是一个一个小时后就过期的令牌。

详细信息可以查看这里: Google 日历 API v3 - 如何获取刷新令牌(Python)

撰写回答