【问题标题】:Google Calendar API missing calendar summaryGoogle Calendar API 缺少日历摘要
【发布时间】:2020-11-23 10:19:52
【问题描述】:

我正在尝试通过 Python 脚本向 Google 添加日历。

相关代码:

with open("primo1.json") as f:
    cal = json.loads(f.read())
calId = cal[0]["title"]
print(calId)

try:
    resCalendar = service.calendars().get(calendarId=calId).execute()
except:
    newCal = {}
    newCal["timeZone"] = "Europe/Rome"
    newCal["summary"] = str(calId.split(" ", 1)[0])
    newCal["kind"] = "calendar#calendar"
    newCal["id"] = str(calId.replace(" ", ""))
    newCal["etag"] = str(hashlib.md5(bencode.bencode(newCal)).hexdigest())
    #print(newCal["etag"])

    newCal = json.dumps(newCal)
    res = service.calendars().insert(body=newCal).execute()
#print(resCalendar)

例外:

Traceback (most recent call last):

File "main.py", line 71, in <module>
    main()
  File "main.py", line 60, in main
    res = service.calendars().insert(body=newCal).execute()
  File "/home/gabriel/.local/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/gabriel/.local/lib/python3.7/site-packages/googleapiclient/http.py", line 915, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars?alt=json returned "Missing summary.". Details: "Missing summary.">

我添加到 newCal dict 的摘要只是一个字符串(在本例中为“ARCHITETTURA”)

完整代码以备不时之需:https://pastebin.com/vQNwjJ0x

【问题讨论】:

    标签: python python-3.x google-api google-calendar-api google-api-python-client


    【解决方案1】:
    • 您正在向请求正文提供 JSON 格式的字符串,由 json.dumps 返回,并且您应该提供字典(请参阅 insert(body=None))。因此,在请求正文中找不到属性summary,并且由于需要此属性(请参阅request body),您将收到错误Missing summary。因此,您应该删除newCal = json.dumps(newCal) 这一行。
    • kindidetag 不是可写属性(参见 Calendar resource representation);它们由 Google 提供,您设置的值将被忽略。因此,在字典中设置这些字段是没有意义的。

    代码sn-p:

    newCal = {
      "summary": "Your summary",
      "timeZone": "Europe/Rome"
    }
    res = service.calendars().insert(body=newCal).execute()
    

    【讨论】:

      【解决方案2】:

      此方法将 JSON 字符串作为其参数。因此,如果您想使用字典,则需要将字典转换为请求正文的 json 字符串。

      您也不需要设置 id、kind 或 etag Google 创建这些值,因为您无法在请求中写入它们。 calendars resource

      文档提供了如何拨打电话Calendar.insert的示例

      calendar = {
          'summary': 'calendarSummary',
          'timeZone': 'America/Los_Angeles'
      }
      
      created_calendar = service.calendars().insert(body=calendar).execute()
      

      【讨论】:

      • 谢谢,完美运行。作为旁注,如果我尝试通过构建字典并将其作为 json 转储来做同样的事情,它就不起作用。如果有人可以解释这种行为,我将把这个问题留一点。
      • 很高兴我能提供帮助
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      相关资源
      最近更新 更多