日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

接口自動化框架里常用的小工具

來源: 責編: 時間:2024-04-03 17:40:09 195觀看
導讀在日常編程工作中,我們常常需要處理各種與時間、數據格式及配置文件相關的問題。本文整理了一系列實用的Python代碼片段,涵蓋了日期時間轉換、數據格式化與轉換、獲取文件注釋以及讀取配置文件等內容,助力開發者提升工作

在日常編程工作中,我們常常需要處理各種與時間、數據格式及配置文件相關的問題。本文整理了一系列實用的Python代碼片段,涵蓋了日期時間轉換、數據格式化與轉換、獲取文件注釋以及讀取配置文件等內容,助力開發者提升工作效率,輕松應對常見任務。MAE28資訊網——每日最新資訊28at.com

MAE28資訊網——每日最新資訊28at.com

1. 秒級與毫秒級時間戳獲取

# 獲取當前秒級時間戳def millisecond(add=0):    return int(time.time()) + add# 獲取當前毫秒級時間戳def millisecond_new():    t = time.time()    return int(round(t * 1000))

這兩個函數分別提供了獲取當前時間的秒級和毫秒級時間戳的功能。millisecond()函數允許傳入一個可選參數add,用于增加指定的時間偏移量。MAE28資訊網——每日最新資訊28at.com

2. 當前日期字符串獲取

MAE28資訊網——每日最新資訊28at.com

#獲取當前時間日期: 20211009def getNowTime(tianshu=0):shijian = int(time.strftime('%Y%m%d')) - tianshuprint(shijian)return shijian

getNowTime()函數返回當前日期(格式為YYYYMMDD),并支持傳入參數tianshu以減去指定天數。該函數適用于需要處理日期型數據且僅關注年月日的情況。MAE28資訊網——每日最新資訊28at.com

3.修復接口返回無引號JSON數據MAE28資訊網——每日最新資訊28at.com

def json_json():    with open("源文件地址", "r") as f, open("目標文件地址", "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)  # 輸出修復后的行                a.write(formatted_line + "/n")            else:                formatted_line = "'" + line.strip().replace(":", "':'").replace(" ", "") + "',"                print(formatted_line)  # 輸出修復后的行                a.write(formatted_line + "/n")        a.write("}")

此函數用于處理從接口復制的未正確格式化的JSON數據,修復缺失的引號,并將其寫入新的文件。源文件與目標文件的路徑需替換為實際路徑。MAE28資訊網——每日最新資訊28at.com

4.將URL查詢字符串轉為JSON

from urllib.parse import urlsplit, parse_qsdef 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()函數接收一個包含查詢字符串的URL,解析其查詢部分,將其轉換為字典形式,并清理多值參數,只保留第一個值。MAE28資訊網——每日最新資訊28at.com

5.文件注釋提取MAE28資訊網——每日最新資訊28at.com

import osdef 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()函數遍歷指定目錄下的.py文件,提取每份文件的第
一行注釋(以#開頭),并將文件名與注釋對應關系寫入指定的文本文件中。

6.讀取配置INI文件

import sysimport osimport configparserclass 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"]
ReadConfig類封裝了對INI配置文件的讀取操作,支持讀取sql.ini和hosts.ini文件。通過實例化該類并指定配置文件路徑,即可方便地獲取所需配置信息。

7.設置全局文件路徑

import osdef 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()函數根據提供的相對路徑,結合當前模塊的絕對路徑,計算出項目根目錄下的目標文件或目錄的絕對路徑,便于在項目中統一管理資源位置。MAE28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-81236-0.html接口自動化框架里常用的小工具

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 面試官:Session和JWT有什么區別?

下一篇: 用Python搭建一個Chatgpt聊天頁面

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 六枝特区| 延津县| 宜春市| 曲靖市| 来凤县| 绵竹市| 获嘉县| 迁安市| 宜黄县| 潢川县| 兴城市| 稷山县| 中江县| 凤冈县| 嘉兴市| 都匀市| 乃东县| 阳泉市| 清河县| 宜宾市| 宜丰县| 吴堡县| 买车| 柞水县| 文水县| 哈尔滨市| 广灵县| 扬中市| 黎川县| 平定县| 龙胜| 卓资县| 辽阳县| 墨竹工卡县| 东丰县| 天门市| 沁水县| 色达县| 黄冈市| 河池市| 万山特区|