接口自動(dòng)化框架里常用的小工具
在日常編程工作中,我們常常需要處理各種與時(shí)間、數(shù)據(jù)格式及配置文件相關(guān)的問題。本文整理了一系列實(shí)用的Python代碼片段,涵蓋了日期時(shí)間轉(zhuǎn)換、數(shù)據(jù)格式化與轉(zhuǎn)換、獲取文件注釋以及讀取配置文件等內(nèi)容,助力開發(fā)者提升工作效率,輕松應(yīng)對(duì)常見任務(wù)。
1. 秒級(jí)與毫秒級(jí)時(shí)間戳獲取
# 獲取當(dāng)前秒級(jí)時(shí)間戳
def millisecond(add=0):
return int(time.time()) + add
# 獲取當(dāng)前毫秒級(jí)時(shí)間戳
def millisecond_new():
t = time.time()
return int(round(t * 1000))
這兩個(gè)函數(shù)分別提供了獲取當(dāng)前時(shí)間的秒級(jí)和毫秒級(jí)時(shí)間戳的功能。millisecond()函數(shù)允許傳入一個(gè)可選參數(shù)add,用于增加指定的時(shí)間偏移量。
2. 當(dāng)前日期字符串獲取
#獲取當(dāng)前時(shí)間日期: 20211009
def getNowTime(tianshu=0):
shijian = int(time.strftime('%Y%m%d')) - tianshu
print(shijian)
return shijian
getNowTime()函數(shù)返回當(dāng)前日期(格式為YYYYMMDD),并支持傳入?yún)?shù)tianshu以減去指定天數(shù)。該函數(shù)適用于需要處理日期型數(shù)據(jù)且僅關(guān)注年月日的情況。
3.修復(fù)接口返回?zé)o引號(hào)JSON數(shù)據(jù)
def json_json():
with open("源文件地址", "r") as f, open("目標(biāo)文件地址", "a+") as a:
a.write("{")
for line in f.readlines():
if "[" in line.strip() or "{" in line.strip():
formatted_line = "'" + line.strip().replace(":", "':").replace(" ", "") + ","
print(formatted_line) # 輸出修復(fù)后的行
a.write(formatted_line + "\n")
else:
formatted_line = "'" + line.strip().replace(":", "':'").replace(" ", "") + "',"
print(formatted_line) # 輸出修復(fù)后的行
a.write(formatted_line + "\n")
a.write("}")
此函數(shù)用于處理從接口復(fù)制的未正確格式化的JSON數(shù)據(jù),修復(fù)缺失的引號(hào),并將其寫入新的文件。源文件與目標(biāo)文件的路徑需替換為實(shí)際路徑。
4.將URL查詢字符串轉(zhuǎn)為JSON
from urllib.parse import urlsplit, parse_qs
def query_json(url):
query = urlsplit(url).query
params = dict(parse_qs(query))
cleaned_params = {k: v[0] for k, v in params.items()}
return cleaned_params
query_json()函數(shù)接收一個(gè)包含查詢字符串的URL,解析其查詢部分,將其轉(zhuǎn)換為字典形式,并清理多值參數(shù),只保留第一個(gè)值。
5.文件注釋提取
import os
def get_first_line_comments(directory, output_file):
python_files = sorted([f for f in os.listdir(directory) if f.endswith('.py') and f != '__init__.py'])
comments_and_files = []
for file in python_files:
filepath = os.path.join(directory, file)
with open(filepath, 'r', encoding='utf-8') as f:
first_line = f.readline().strip()
if first_line.startswith('#'):
comment = first_line[1:].strip()
comments_and_files.append((file, comment))
with open(output_file, 'w', encoding='utf-8') as out:
for filename, comment in comments_and_files:
out.write(f"{filename}: {comment}\n")
# 示例用法
get_first_line_comments('指定文件夾', '指定生成文件路徑.txt')
get_first_line_comments()函數(shù)遍歷指定目錄下的.py文件,提取每份文件的第
6.讀取配置INI文件
import sys
import os
import configparser
class ReadConfig:
def __init__(self, config_path):
self.path = config_path
def read_sqlConfig(self, fileName="sql.ini"):
read_mysqlExecuteCon = configparser.ConfigParser()
read_mysqlExecuteCon.read(os.path.join(self.path, fileName), encoding="utf-8")
return read_mysqlExecuteCon._sections
def read_hostsConfig(self, fileName="hosts.ini"):
read_hostsCon = configparser.ConfigParser()
read_hostsCon.read(os.path.join(self.path, fileName), encoding="utf-8")
return read_hostsCon._sections
# 示例用法
config_reader = ReadConfig('配置文件所在路徑')
sql_config = config_reader.read_sqlConfig()
hosts_config = config_reader.read_hostsConfig()["hosts"]
7.設(shè)置全局文件路徑
import os
def setFilePath(filePath):
current_module_path = os.path.dirname(os.path.abspath(__file__))
project_root_path = os.path.dirname(os.path.dirname(current_module_path))
path = os.path.join(project_root_path, filePath.lstrip('/'))
return os.path.abspath(path)
# 示例用法
confPath = setFilePath("地址文件路徑")
setFilePath()函數(shù)根據(jù)提供的相對(duì)路徑,結(jié)合當(dāng)前模塊的絕對(duì)路徑,計(jì)算出項(xiàng)目根目錄下的目標(biāo)文件或目錄的絕對(duì)路徑,便于在項(xiàng)目中統(tǒng)一管理資源位置。