Python一些提高效率的類庫和裝飾器用法

韩凯1990發表於2024-07-24

本文主要是慢慢積累Python中一些能提高效率的類庫和裝飾器,閒話少說,開始進入主題。

一、重試

【問題引申:介面網路抖動不穩如何做?回答:請求介面捕獲異常和介面請求重試】

1 from retrying import retry
2 # 等待1秒後重試,最大重試次數為3
3 @retry(stop_max_attempt_number=3, wait_fixed=1000)
4 def test_foo():
5     pass

二、介面返回值深度校驗

【問題引申:介面返回值如何做校驗?回答:用deepdiff可以做返回值型別及值不一致的校驗】

 1 from deepdiff import DeepDiff
 2 def vaildate_json(expected, actual):
 3     #  比較兩個JSON物件的差異
 4     diff = DeepDiff(expected, actual)
 5     #  輸出差異
 6     if diff:
 7         print("實際結果與預期結果不一致:")
 8         print(diff)
 9         return False
10     else:
11         print("實際結果與預期結果一致")
12         return True
13 
14 # 需要比較的JSON物件
15 expected = {
16     "key1":33,
17     "key2":{
18         "nested_key":"value",
19         "nested_list":[2,3,4]
20     }
21 }
22 actual = {
23     "key1":"33",
24     "key2":{
25         "nested_key":"value",
26         "nested_list":[2,3,4]
27     }
28 }
29 #  呼叫函式進行比較
30 vaildate_json(expected,actual)

三、介面返回值取值:jsonpath

【問題引申:如何快速方便的獲取json中的某一個值?回答:用jsonpath】

 1 import jsonpath
 2 actual = {
 3     "key1":"33",
 4     "key2":{
 5         "nested_key":"value",
 6         "key1":"hankai",
 7         "nested_list":[2,3,4]
 8    }
 9  }
10 list1 = jsonpath.jsonpath(actual,'$..key1')
11 print(list1)  # ['33', 'hankai']

四、讀取Excel並轉換成列表:xToolkit

【問題引申:如何遍歷Excel做介面自動化?回答:xToolkit庫】

 1 from xToolkit import xfile
 2 
 3 # 讀取Excel資料轉換成列表
 4 testdata = xfile.read("介面測試用例.xls").excel_to_dict(sheet=1)
 5 print(testdata)
 6 """
 7 [
 8     {'描述': '使用者登入', '用例編號': 'shop_api_001', '介面URL': 'http://shoo.hu.com/index.php?s=api/user/login', '請求方式': 'post', 'URL引數': '{"application":"app","application_client_type": "weixin",}', '表單引數': '', 'JSON引數': ' {"accounts":"ce_hk","pwd": 123456,"type":"username"}', '預期狀態碼': 200, '預期返回內容': '', '備註': '', '提取引數': 'token', '需要引數': ''},
 9     {'描述': '加入購物車', '用例編號': 'shop_api_002', '介面URL': 'http://shoo.hu.com/index.php?s=api/cart/save', '請求方式': 'post', 'URL引數': '{"application":"app","application_client_type": "weixin",}', '表單引數': '', 'JSON引數': '{"goods_id": "2","spec": [{"type": "套餐","value": "套餐二"},{"type": "顏色","value": "銀色"},{"type": "容量","value": "64G"}],"stock": 1}', '預期狀態碼': 200, '預期返回內容': '', '備註': '', '提取引數': '', '需要引數': 'token'}
10  ]
11 """

五、json

 1 import json
 2 
 3 # 定義一個字典
 4 data = {
 5     "name": "張三",
 6     "age": 20,
 7     "city": "北京"
 8 }
 9 json.dumps(data)  # 字典編碼成JSON字串
10 json.loads(data)  # JSON字串解碼為字典
11 
12 json.dump(data, open("data.json", "w"))  # 字典編碼成JSON字串並寫入檔案
13 json.load(open("data.json", "r"))  # 從檔案中讀取JSON字串並解碼為字典

六、time

import time
print(time.asctime()) # Wed Apr 24 17:33:12 2024
print(time.time()) # 1713951192.7047122
print(time.localtime()) # time.struct_time(tm_year=2018, tm_mon=8, tm_mday=8, tm_hour=12, tm_min=12, tm_sec=12, tm_wday=2, tm_yday=220, tm_isdst=0)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 2024-04-24 17:33:12
import datetime

# 獲取當前時間
now = datetime.datetime.now()
# 計算時間
start_time = now + datetime.timedelta(days=1)
end_time = now + datetime.timedelta(days=30)
# 格式化輸出年月日時分秒
start_time = start_time.strftime("%Y-%m-%d %H:%M:%S")
end_time = end_time.strftime("%Y-%m-%d %H:%M:%S")
print("開始時間是:", start_time)    開始時間是: 2024-07-18 08:19:33
print("結束時間是:", end_time)      結束時間是: 2024-08-16 08:19:33
# 獲取當前時間週一和週日
import datetime
def get_current_week():
    monday, sunday = datetime.date.today(), datetime.date.today()
    one_day = datetime.timedelta(days=1)
    while monday.weekday() != 0:
        monday -= one_day
    while sunday.weekday() != 6:
        sunday += one_day
    # return monday, sunday
    # 返回時間字串
    return datetime.datetime.strftime(monday, "%Y-%m-%d"), datetime.datetime.strftime(sunday, "%Y-%m-%d")
    
print("週一是:",get_current_week()[0])  //週一是: 2024-07-22
print("週日是:",get_current_week()[1])  //週日是: 2024-07-28

# 今天年月日
now = datetime.datetime.now().strftime("%Y-%m-%d")
print(now) //列印今天的年月日


# 日期獲取周幾
from datetime import datetime, timedelta
def get_weekday(start_date, end_date, today_date):
    # 將日期字串轉換為日期物件
    start_date = datetime.strptime(start_date, "%Y-%m-%d")
    end_date = datetime.strptime(end_date, "%Y-%m-%d")
    today_date = datetime.strptime(today_date, "%Y-%m-%d")
    # 計算週一到週日的天數
    days_between = (end_date - start_date).days
    # 計算今天和週一之間的天數差
    days_from_monday = (today_date - start_date).days
    # 計算今天是周幾,0代表週一,1代表週二,以此類推
    weekday = days_from_monday % 7
    # 返回周幾的名稱
    weekdays = ["週一", "週二", "週三", "週四", "週五", "週六", "週日"]
    return weekdays[weekday]

# 示例
start_date = "2024-07-22"  # 週一的日期
end_date = "2024-07-28"    # 週日的日期
today_date = "2024-07-24"  # 今天的日期

print("今天是:", get_weekday(start_date, end_date, today_date)) //今天是: 週三

七、隨機數生成

import random
# 生成10位隨機數
print (''.join(str(random.choice(range(10))) for _ in range(10)))

相關文章