[英]Google Calendar API: HttpError 400 creating event in google calendar
我制作了一個程序,它可以讓我下班並將它們作為事件導入 Google 日歷。 去年它運行得很好,但是當我今天運行它時,我得到了 400 httperror。
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json returned "Bad Request". Details: "[{'domain': 'global', 'reason': 'badRequest', 'message': 'Bad Request'}]">
我不知道是什么導致了它的發生。 我從其他論壇上讀到它可能與時區有關,但自從它制作以來我沒有在這個程序中更改過任何一行。 不過,我已經更新了 chromedriver 幾次。
from __future__ import nested_scopes, print_function
import datetime
from os import R_OK
import os.path
from random import Random
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from selenium import webdriver
from selenium.webdriver.common.by import By
import re
# ------------------------------------------------------------------------------------------------
n = 0
ArbejdsTider = []
# Information
UsernameText = "my email"
PasswordText = "my password"
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"
options = webdriver.ChromeOptions()
options.headless = True
options.add_argument(f'user-agent={user_agent}')
options.add_argument("--window-size=1920,1080")
options.add_argument('--ignore-certificate-errors')
options.add_argument('--allow-running-insecure-content')
options.add_argument("--disable-extensions")
options.add_argument("--proxy-server='direct://'")
options.add_argument("--proxy-bypass-list=*")
options.add_argument("--start-maximized")
options.add_argument('--disable-gpu')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
driver = webdriver.Chrome(executable_path="chromedriver.exe", options=options)
# Kom ind på siden
driver.get(
"https://app.tamigo.com/Shift/Pages/EmployeeShifts.aspx")
# Find username textbox og indsæt username
UsernameInput = driver.find_element(By.ID, 'Username')
UsernameInput.send_keys(UsernameText)
# Find password textbox og indsæt password
PasswordInput = driver.find_element(By.ID, 'Password')
PasswordInput.send_keys(PasswordText)
# Find log-in knap og tryk
LoginBtn = driver.find_element(By.ID, 'login-btn').click()
# Find tabel
RawData = driver.find_element(By.XPATH, '//*[@id="employeeShiftsGrid"]/tbody')
# Gemmer de forskellige vagter i lister [[dag1, tid2], [dag2,tid2], [dag3,tid3]]
for row in RawData.find_elements(By.TAG_NAME, "tr"):
n += 1
dag = driver.find_element(
By.XPATH, "//*[@id='employeeShiftsGrid']/tbody/tr[{}]/td[4]".format(n)).text
tid = driver.find_element(
By.XPATH, "//*[@id='employeeShiftsGrid']/tbody/tr[{}]/td[5]".format(n)).text
ArbejdsTider.append([dag, tid])
# Filtrer dagenavne væk
for x in range(len(ArbejdsTider)):
ArbejdsTider[x][0] = re.sub('\D', '', ArbejdsTider[x][0])
ArbejdsTider[x][1] = re.sub('\D', '', ArbejdsTider[x][1])
# Filterer 2-tal væk i tid ved evt. pause i vagten
for x in range(len(ArbejdsTider)):
if len(ArbejdsTider[x][1]) > 8:
ArbejdsTider[x][1] = ArbejdsTider[x][1][:-1]
# for x in range(len(ArbejdsTider)):
# print(ArbejdsTider[x][0])
# print(ArbejdsTider[x][1])
# driver.get_screenshot_as_file("screenshot.png")
# ------------------------------------------------------------------------------------------------
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/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(
'C:/Users/rasmu/Desktop/TTC/Calendar/credentials.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())
service = build('calendar', 'v3', credentials=creds)
# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=100, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
print('No upcoming events found.')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
if event['summary'] == "Arbejde":
# Slet vagt
service.events().delete(calendarId='primary',
eventId=event['id']).execute()
# print("Delete the event and create a new one")
# print(start, event['summary'])
for x in range(len(ArbejdsTider)):
tidspunkt = str(ArbejdsTider[x][1][4]) + str(ArbejdsTider[x][1][5])
STARTÅR = int(str(ArbejdsTider[x][0][4]) + str(ArbejdsTider[x][0]
[5]) + str(ArbejdsTider[x][0][6]) + str(ArbejdsTider[x][0][7]))
STARTMÅNED = int(str(ArbejdsTider[x][0][2]) + str(ArbejdsTider[x][0][3]))
STARTDAG = int(str(ArbejdsTider[x][0][0]) + str(ArbejdsTider[x][0][1]))
STARTTIME = int(str(ArbejdsTider[x][1][0]) + str(ArbejdsTider[x][1][1]))
STARTMINUT = int(str(ArbejdsTider[x][1][2]) + str(ArbejdsTider[x][1][3]))
SLUTÅR = int(str(ArbejdsTider[x][0][4]) + str(ArbejdsTider[x][0]
[5]) + str(ArbejdsTider[x][0][6]) + str(ArbejdsTider[x][0][7]))
SLUTMÅNED = int(str(ArbejdsTider[x][0][2]) + str(ArbejdsTider[x][0][3]))
SLUTDAG = int(str(ArbejdsTider[x][0][0] + str(ArbejdsTider[x][0][1])))
SLUTTIME = int(str(ArbejdsTider[x][1][4]) + str(ArbejdsTider[x][1][5]))
SLUTMINUT = int(str(ArbejdsTider[x][1][6]) + str(ArbejdsTider[x][1][7]))
# Vagt slutter efter midnat
if int(tidspunkt) >= 0 and int(tidspunkt) < 4:
event = {
'summary': 'Arbejde',
'start': {
'dateTime': '{}-{}-{}T{}:{}:00'.format(STARTÅR, STARTMÅNED, STARTDAG, STARTTIME, STARTMINUT),
'timeZone': 'GMT+02:00',
},
'end': {
'dateTime': '{}-{}-{}T{}:{}:00'.format(SLUTÅR, SLUTMÅNED, SLUTDAG+1, SLUTTIME, SLUTMINUT),
'timeZone': 'GMT+02:00',
}
}
event = service.events().insert(calendarId='primary', body=event).execute()
# Vagt slutter før midnat
else:
event = {
'summary': 'Arbejde',
'start': {
'dateTime': '{}-{}-{}T{}:{}:00'.format(STARTÅR, STARTMÅNED, STARTDAG, STARTTIME, STARTMINUT),
'timeZone': 'GMT+02:00',
},
'end': {
'dateTime': '{}-{}-{}T{}:{}:00'.format(SLUTÅR, SLUTMÅNED, SLUTDAG, SLUTTIME, SLUTMINUT),
'timeZone': 'GMT+02:00',
}
}
event = service.events().insert(calendarId='primary', body=event).execute()
錯誤代碼400表示未提供必填字段或參數,提供的值無效,或提供的字段組合無效。
您可以通過在請求正文的dateTime值中提供以下任一值來復制錯誤:
例子:
失效日期:
輸出:
An error occurred: <HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json returned "Bad Request". Details: "[{'domain': 'global', 'reason': 'badRequest', 'message': 'Bad Request'}]">
要解決此問題,請確保驗證傳遞給代碼的dateTime部分的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.