获取列表事件时如何在python中获取Google Calendar API status_code 答案:代码示例:进一步阅读:

问题描述

我尝试使用Google Calendar API

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

我有权访问calendarId时,一切都很好,但是如果我没有calendarId许可,那么一切都会出错。

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

如何获取status_code,例如,如果为404,则python将通过

-------------------------------解决方案--------------- ----------

非常感谢 @Rafa Guillermo 我使新功能返回status_code:)

def response_status_code(service,calendarId):
    Now = datetime.utcNow().isoformat() + 'Z'
    try:
        events_result = service.events().list(calendarId=calendarId,orderBy='startTime').execute()
        status_code = 200
    except Exception as e:
        print(json.loads(e.content)['error']['code'])
        status_code = json.loads(e.content)['error']['code']
    return status_code

解决方法

答案:

您可以在循环中使用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

我希望这对您有帮助!

进一步阅读:

,

感谢@Rafa Guillermo

我为autoload.py程序编写了完整的代码,但我也想知道如何获取请求google API的respose 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)