簡體   English   中英

獲取列表事件時,如何在 Python 中獲取 Google 日歷 API status_code?

[英]How can I get Google Calendar API status_code in Python when get list events?

我嘗試使用谷歌日歷 API

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

一切正常,當我有訪問calendarId的權限時,但是當我沒有calendarId權限時,如果錯誤就會出錯。

我構建了一個 autoload.py function,計划為 python 每 10 分鍾加載一次事件,如果出現錯誤,這個 function 將停止,我必須使用 SSH 終端手動重啟 autoload.py 所以我想知道:

我如何獲得status_code,例如,如果它是404,python將通過

回答:

您可以在所有日歷的循環中使用 try/except 塊到 go,並跳過引發錯誤的訪問。

代碼示例:

要獲取錯誤代碼,請確保導入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 程序,但我也想知道如何獲得響應 json 或請求 Google API 的狀態代碼。

解決方案:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM