8

我想访问 Google Calendar API 以使用 Python 插入条目。我在 Google API 控制台上创建了一个服务帐户,添加了一个私钥,然后下载了它。

但是当我尝试修改日历的任何内容时,它在同一个帐户上,我收到以下错误消息。阅读作品。

代码是

import httplib2

from oauth2client.client import SignedJwtAssertionCredentials 
from apiclient.discovery import build

event = {
         'summary' : 'Appointment',
         'location' : 'Somewhere',
         'start' : {
                    'dateTime' : '2012-09-03T10:00:00.000-07:00'
                    },
         'end' :    {
                 'dateTime' : '2012-09-03T10:25:00.000-07:00'
                    }
}


f = file("key.p12", "rb")
key = f.read()
f.close()

credentials = SignedJwtAssertionCredentials(
                                                service_account_name='423291807109-XXXXXXXXXXXXXXXXxx@developer.gserviceaccount.com',
                                                private_key=key,

                                                scope='https://www.googleapis.com/auth/calendar'                                            
                                            )

http = httplib2.Http()
http = credentials.authorize(http)

service = build('calendar', 'v3', http=http)
request = service.events().insert(calendarId='XXXXXXXXXXXXXXXXXX@group.calendar.google.com', body=event)

response = request.execute()

print(response)

错误信息是:

apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/XXXXXXXXXXXXXXXXXXX@group.calendar.google.com/events?alt=json returned "Forbidden">

我原以为我可以使用此服务帐户访问我自己的数据,但似乎并非如此。

谷歌声称

创建服务帐户后,您还可以访问与私钥关联的客户端 ID。在编写应用程序时,您将需要两者。- https://developers.google.com/accounts/docs/OAuth2?hl=de#scenarios

我用谷歌搜索了大约 2 个小时,但似乎记录得很糟糕。有没有一种方法可以通过谷歌日历 API 插入新事件而无需用户交互(又名 3 腿 OAuth),或者有没有办法修复它?

我刚刚发现已弃用的 ClientLoging。为什么谷歌让它变得如此困难?

亲切的问候

4

1 回答 1

1

我意识到,如果将生成的凭据转储到 JSON 并在每次需要时读取它们,那么 3 步 OAuth 就可以工作。

所以流程是:将您的client_secrets.json添加到与此脚本相同的文件夹中,如Google API中所述。从提示中给出的 url 中获取密钥。根据提示输入它。派对!11。我希望这些凭据永远存在。

from oauth2client.client import flow_from_clientsecrets

flow = flow_from_clientsecrets('client_secrets.json',
                               scope='https://www.googleapis.com/auth/calendar',
                               redirect_uri='urn:ietf:wg:oauth:2.0:oob')

auth_uri = flow.step1_get_authorize_url()
print('Visit this site!')
print(auth_uri)
code = raw_input('Insert the given code!')
credentials = flow.step2_exchange(code)
print(credentials)

with open('credentials', 'wr') as f:
    f.write(credentials.to_json())

现在,在应用程序本身:

def __create_service():
    with open('credentials', 'rw') as f:
        credentials = Credentials.new_from_json(f.read())

    http = httplib2.Http()
    http = credentials.authorize(http)

    return build('calendar', 'v3', http=http)

要获取服务对象,现在可以调用

service = __create_service()

并在其上使用 API。

于 2012-09-04T18:50:34.237 回答