rei*_*eer 7 python authentication api calendar google-api-python-client
我想访问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)
Run Code Online (Sandbox Code Playgroud)
错误信息是:
apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/XXXXXXXXXXXXXXXXXXX@group.calendar.google.com/events?alt=json returned "Forbidden">
Run Code Online (Sandbox Code Playgroud)
我原本以为我可以使用这个服务帐户访问我自己的数据,但似乎不是.
谷歌声称
创建服务帐户后,您还可以访问与私钥关联的客户端ID.编写应用程序时,您将需要两者.- https://developers.google.com/accounts/docs/OAuth2?hl=de#scenarios
我用Google搜索了大约2个小时,但似乎记录得非常糟糕.有没有办法可以通过Google Calendar API插入新活动而无需用户互动(也就是三足OAuth),还是有办法解决这个问题?
我刚发现已弃用的ClientLoging.为什么Google会让它变得那么困难?
亲切的问候
我意识到,如果将生成的凭据转储到 JSON 并在每次需要时读取它们,那么 3 步式 OAuth 就可以工作。
因此流程是:按照Google API中的说明将client_secrets.json添加到与此脚本相同的文件夹中。从提示中给出的 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())
Run Code Online (Sandbox Code Playgroud)
现在,在应用程序本身中:
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)
Run Code Online (Sandbox Code Playgroud)
要获取服务对象,现在可以调用
service = __create_service()
Run Code Online (Sandbox Code Playgroud)
并在其上使用 API。
归档时间: |
|
查看次数: |
3463 次 |
最近记录: |