【问题标题】:How can I get Google Calendar API status_code in Python when get list events?获取列表事件时如何在 Python 中获取 Google Calendar API status_code?
【发布时间】:2020-12-08 06:10:33
【问题描述】:

我尝试使用 Google Calendar API

events_result = service.events().list(calendarId=calendarId,
                                          timeMax=now,
                                          alwaysIncludeEmail=True,
                                          maxResults=100, singleEvents=True,
                                          orderBy='startTime').execute()

当我有访问calendarId的权限时一切正常,但是当我没有calendarId权限时如果出错就会出错。

我使用 schedule python 构建了一个 autoload.py 函数,每 10 分钟加载一次事件,如果出现错误,该函数将停止,我必须使用 SSH 终端手动重新启动 autoload.py 所以我想知道:

如何获取status_code,例如如果是404,python会PASS

【问题讨论】:

    标签: python google-api http-status-code-404 google-calendar-api google-api-python-client


    【解决方案1】:

    答案:

    您可以在循环中使用 try/except 块来遍历所有日历,并跳过引发错误的访问。

    代码示例:

    要获取错误代码,请确保导入json:

    import json
    

    然后就可以从异常中得到错误码了:

    calendarIds = ["calendar ID 1", "calendar ID 2", "calendar Id 3", "etc"]
    
    for i in calendarIds:
        try:
            events_result = service.events().list(calendarId=i,
                                              timeMax=now,
                                              alwaysIncludeEmail=True,
                                              maxResults=100, singleEvents=True,
                                              orderBy='startTime').execute()
        except Exception as e:
            print(json.loads(e.content)['error']['code'])
            continue
    

    延伸阅读:

    【讨论】:

      【解决方案2】:

      感谢@Rafa Guillermo,我将完整代码上传到了autoload.py程序,但我也想知道,如何获取请求Google API的响应json或status_code。

      解决办法:

      try:
       code here
      except Exception as e:
                  continue
      
      import schedule
      import time
      from datetime import datetime
      import dir
      import sqlite3
      from project.function import cmsCalendar as cal
      db_file = str(dir.dir) + '/admin.sqlite'
      
      def get_list_shop_from_db(db_file):
          cur = sqlite3.connect(db_file).cursor()
          query = cur.execute('SELECT * FROM Shop')
          colname = [ d[0] for d in query.description ]
          result_list = [ dict(zip(colname, r)) for r in query.fetchall() ]
          cur.close()
          cur.connection.close()
          return result_list
      
      def auto_load_google_database(list_shop, calendarError=False):
          shopId = 0
          for shop in list_shop:
              try:
                  shopId = shopId+1
                  print("dang ghi vao shop", shopId)
                  service = cal.service_build()
                  shop_step_time_db = list_shop[shopId]['shop_step_time']
                  shop_duration_db = list_shop[shopId]['shop_duration']
                  slot_available = list_shop[shopId]['shop_slots']
                  slot_available = int(slot_available)
                  workers = list_shop[shopId]['shop_workers']
                  workers = int(workers)
                  calendarId = list_shop[shopId]['shop_calendarId']
                  if slot_available > workers:
                      a = workers
                  else:
                      a = slot_available
                  if shop_duration_db == None:
                      shop_duration_db = '30'
                  if shop_step_time_db == None:
                      shop_step_time_db = '15'
      
                  shop_duration = int(shop_duration_db)
                  shop_step_time = int(shop_step_time_db)
      
                  shop_start_time = list_shop[shopId]['shop_start_time']
                  shop_start_time = datetime.strptime(shop_start_time, "%H:%M:%S.%f").time()
                  shop_end_time = list_shop[shopId]['shop_end_time']
                  shop_end_time = datetime.strptime(shop_end_time, "%H:%M:%S.%f").time()
      
                  # nang luc moi khung gio lay ra tu file Json WorkShop.js
                  booking_status = cal.auto_load_listtimes(service, shopId, calendarId, shop_step_time, shop_duration, a,
                                                           shop_start_time,
                                                           shop_end_time)
      
      
              except Exception as e:
                  continue
      
      def main():
      
          list_shop = get_list_shop_from_db(db_file)
          auto_load_google_database(list_shop)
      
      if __name__ == '__main__':
          main()
          schedule.every(5).minutes.do(main)
          while True:
              # Checks whether a scheduled task
              # is pending to run or not
              schedule.run_pending()
              time.sleep(1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-09
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 2015-08-10
        • 1970-01-01
        • 1970-01-01
        • 2014-03-13
        相关资源
        最近更新 更多