gpt4 book ai didi

python - 谷歌日历 API : Error code 403: The request is missing a valid API key

转载 作者:行者123 更新时间:2023-12-05 02:35:36 29 4
gpt4 key购买 nike

最近我开始尝试使用 Google 的日历 API 来为自己制作一个个人应用程序,该应用程序可以随机创建每日亮点,然后在将其传递到我的谷歌日历之前利用它们制作事件。我对这类事情的经验很少,几乎没有,但谷歌的快速入门指南让我在一个不错的地方设置。我几乎只是采用了他们提供的 Quickstart python 代码,添加了一些我自己的函数来创建和删除事件,并调整了范围以包括创建和删除所述事件的权限。我使用的代码:

from __future__ import print_function

import datetime
from hashlib import new
import os.path
from re import S

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

from highlightsGenerator import *

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly',
'https://www.googleapis.com/auth/calendar.events',
'https://www.googleapis.com/auth/calendar']

templateEvent = {
'summary': 'Daily Highlight',
'description': '',
'start': {
'dateTime': '',
},
'end': {
'dateTime': '',
},
'reminders': {
'useDefault': True,
},
}

def createHighlightEvents(service):
workingDate = datetime.date.today()
workingDate += datetime.timedelta(days=1)
highlightSchedule = scheduleGenerator()
print(highlightSchedule)
for k in highlightSchedule:
newEvent = templateEvent
newEvent['description'] = k
newEvent['start']['dateTime'] = str(workingDate) + 'T13:00:00+3:00'
newEvent['end']['dateTime'] = str(workingDate) + 'T17:00:00+03:00'
service.events().insert(calendarId='primary', body=newEvent).execute()
workingDate += datetime.timedelta(days=1)

def deleteHighlightEvents(service):
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
events_result = service.events().list(calendarId='primary', q='Daily Highlight',timeMin=now,
maxResults=20, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])

# if not events:
# print('No upcoming events found.')
# return

for event in events:
eID = event['id']
service.events().delete(calendarId='primary', eventId=eID).execute()

def reRollHighlightEvents(service):
deleteHighlightEvents(service)
createHighlightEvents(service)

def getDate(dateTime):
dateStr = dateTime[:len(dateTime) - 6]
date = datetime.datetime.strptime(dateStr, '%Y-%m-%dT%H:%M:%S')
return date

def shiftHighlights(service, numDays):
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
events_result = service.events().list(calendarId='primary', q='Daily Highlight',timeMin=now,
maxResults=20, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])

if not events:
print('No upcoming events found.')
return

for event in events:
newStartDate = getDate(event['start']['dateTime']) + datetime.timedelta(days=numDays)
newEndDate = getDate(event['end']['dateTime']) + datetime.timedelta(days=numDays)
newStartDateStr = 'T'.join([str(newStartDate.date()), str(newStartDate.time())])
newEndDateStr = 'T'.join([str(newEndDate.date()), str(newEndDate.time())])
newEvent = event
newEvent['start']['dateTime'] = newStartDateStr + '+03:00'
newEvent['end']['dateTime'] = newEndDateStr + '+03:00'

service.events().update(calendarId='primary', eventId=event['id'], body=newEvent).execute()



def main():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'client_secret_158794507060-ucqbqgapmlf7lmvre6knjc5nehd00ms0.apps.googleusercontent.com.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())

try:
service = build('calendar', 'v3', credentials=creds)

# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])

if not events:
print('No upcoming events found.')
return

# Prints the start and name of the next 10 events
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])

userInput = input('Create (c), Delete (d), Re-Roll (r), Shift (s) highlights?\n')
if userInput == 'c':
createHighlightEvents(service)
elif userInput == 'd':
deleteHighlightEvents(service)
elif userInput == 'r':
reRollHighlightEvents(service)
elif userInput == 's':
numDays = input('How many days would you like to shift by? (x) to cancel\n')
if numDays != 'x' and numDays.isnumeric:
shiftHighlights(service, int(numDays))
elif numDays != 'x':
print('Please input a number or (x) to cancel')
else:
print('That is not one of the options')

except HttpError as error:
print('An error occurred: %s' % error)


if __name__ == '__main__':
main()

我设法让它做我想做的事,基本上就是这样,但是当我昨天尝试运行它时,它给出了一个错误请求的 http 400 错误。单击它提供的链接给了我这个:

{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"errors": [
{
"message": "The request is missing a valid API key.",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}

现在您可能已经看到,我留在代码中用于检索和显示前 10 个即将发生的事件。它仍然能够正常运行,但如果尝试创建事件或删除事件,则会显示此错误消息。我对这条消息感到很困惑,因为我已经完成了我认为需要的所有授权。我的客户端密码没有改变,但即便如此,我还是重新下载了它,看看它是否会做任何事情,但它没有。我删除了 token 并让它一次又一次地运行授权,我给予了许可。这也被证明是徒劳的,据我所知,我的示波器还不错。

这里有几个问题有类似的错误,但他们似乎出于与我不同的原因(据我所知)或者因为他们缺少我认为我已经拥有的授权。

同样,我对这类事情几乎没有经验,所以可能有一些非常明显的事情我没有做,但恐怕我真的不知道那可能是什么。

如果您能提供任何帮助,我们将不胜感激

最佳答案

我已经重新创建并运行了您的代码,但我无法遇到 403。代码看起来不错,应该可以工作,特别是因为您可以使用列表命令检索数据。这不是一个明确的答案,但要使其正常工作,您可以尝试:

  • 在禁用和启用日历 API 后重新下载 credentials.json 文件。
  • 仅使用 'https://www.googleapis.com/auth/calendar' 范围,因为这是限制最少的范围,也是创建事件所需的范围。
  • 删除 token.json 文件以强制 OAuth 让您重新登录。

尽管如此,我确实设法找到了一个错误,该错误会导致您的代码在启动和运行时失败。 'start''end' 属性同时需要 'dateTime''timeZone' 属性作为它是在 this 中完成的例子。因此这段代码会失败:

newEvent['start']['dateTime'] = str(workingDate) + 'T13:00:00+3:00'
newEvent['end']['dateTime'] = str(workingDate) + 'T17:00:00+03:00'

并且应该替换为这个:

newEvent['start']['dateTime'] = str(workingDate) + 'T13:00:00'
newEvent['start']['timeZone'] = 'Your timeZone'
newEvent['end']['dateTime'] = str(workingDate) + 'T17:00:00'#Having the +3:00 will fail
newEvent['end']['timeZone'] = 'Your timeZone'

当然,您可以在维基百科中找到您的时区:https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

关于python - 谷歌日历 API : Error code 403: The request is missing a valid API key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70495445/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com