In a django application, I try to have RW access to a google calendar which I own myself.
Tried several ways with a service account & client secrets, but all resulting in authentication errors.
The API explorer works, but it requests consent in a popup window, which is obviously not acceptable.
Documentation on google OAuth2 describes several scenarios. Probably "web server application" applies here? It says:
"The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. Google handles the user authentication, session selection, and user consent. The result is an authorization code, which the application can exchange for an access token and a refresh token."
Again, we do not want a browser redirection, we want direct access to the google calendar.
So question is: how can a django server access a google calendar, on which I have full rights, view events and add events using a simple server stored key or similar mechanism?
答案 0 :(得分:1)
在DalmTo和great article的帮助下,我获得了使用python代码处理谷歌日历的RW访问权限。我将在此总结解决方案。
以下是步骤:
首先注册Google服务帐户:服务帐户是预先授权的帐户,可避免您每次都需要获得同意或刷新密钥: https://developers.google.com/identity/protocols/OAuth2ServiceAccount (可以忽略G-suite上的部分)
下载服务帐户凭据并安全存储。你的python代码需要访问这个文件。
转到您想要访问的Google日历。 例如https://calendar.google.com/calendar/r/month 在右侧,您可以看到日历。创建一个额外的测试(因为我们很快就会写到它)。然后指向此新日历:单击其旁边的3个点并编辑共享设置。将服务帐户电子邮件地址添加到“与特定人员共享”下的共享中。 (您可以在先前在“client_email”下找到的文件中找到服务帐户电子邮件地址) 在同一个屏幕中,请注意“日历ID”,您需要在下面的代码中使用它。
现在,您的服务帐户拥有日历的RW权限。
使用网络用户界面(https://calendar.google.com/calendar/r/month)向日历添加至少一个事件,以便我们可以从下面的代码中进行阅读和更改。
然后使用以下python代码来阅读日历并更改事件。
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = '<path to your service account file>'
CAL_ID = '<your calendar ID>'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials)
events_result = service.events().list(calendarId=CAL_ID).execute()
events = events_result.get('items', [])
event_id = events[0]['id']
event = events[0]
service.events().update(calendarId=CAL_ID, eventId=event_id, body={"end":{"date":"2018-03-25"},"start":{"date":"2018-03-25"},"summary":"Kilroy was here"}).execute()
然后你去......阅读一个活动并更新活动。