問題:當(dāng)參數(shù)為動(dòng)態(tài)參數(shù)時(shí),Template替換無法進(jìn)行二次處理
解決方案:通過熱加載來進(jìn)行替換
熱加載原理:在代碼運(yùn)行的過程中動(dòng)態(tài)的調(diào)用python中的方法達(dá)到獲得動(dòng)態(tài)參數(shù)
可以進(jìn)行熱加載的情況:yaml文件,隨機(jī)數(shù),替換后的值進(jìn)行計(jì)算,加密等
示例:
需要熱加載的數(shù)據(jù):
yaml數(shù)據(jù):extract.yaml
token: 76_ZgYcDxWFgCCjZVj2EPfqj7QWW_k3-iUZq68Mr6hE_VvDDa_IAfjEIi7nQwMUoISer8MAspesP1JnP1iIziezVPcB4jqZs4z_3EQpVtkEVm0Z0L7VyTmQV7JC0gsTYGaAAAPUC
需要操作的數(shù)據(jù)
class DeBugTalk:
#場景一:讀取yaml中的數(shù)據(jù)
def read_yaml(self,key):
with open("D:\study\pytest\extract.yaml", encoding="utf-8") as f:
value = yaml.safe_load(f)
return value[key]
# 場景二:數(shù)據(jù)計(jì)算
def add(self,a,b):
return str(int(a)+int(b))
# 場景三:讀取隨機(jī)數(shù)
def random(self):
return str(random.randint(1, 10))
熱加載方法
class ExtractUtil:
def hotload_replace(self,data_str:str):
# 1.定義一個(gè)正則匹配的通用表達(dá)式
# regexp = "\\$\\{(.*?)\\}" # 用于匹配格式為:${access_token}
regexp = "\\$\\{(.*?)\\((.*?)\\)\\}" # 用于匹配格式為:${函數(shù)名(參數(shù))}
fun_list = re.findall(regexp,data_str)
for f in fun_list:
print(f)
# ${函數(shù)名(參數(shù))} >>函數(shù)名=f[0],參數(shù)為=f[1]
if f[1] == "": # 當(dāng)f[1]沒有參數(shù)為''時(shí)
value = getattr(DeBugTalk(), f[0])() # >>此時(shí)通過反射調(diào)用了random()和dm5()方法
else: # 當(dāng)f[1]有參數(shù)時(shí)
value = getattr(DeBugTalk(), f[0])(*f[1].split(","))
# 如果value的值為字符串格式,但是時(shí)數(shù)字,為了看著清楚明白,可以加一層處理
if isinstance(value, str) and value.isdigit():
value = "'" + value + "'"
print('value:%s' % value, type(value)) # 注意這里的打印是在if同級(jí),不然不滿足的數(shù)據(jù)無法打印
# 拼接舊的值
old_value = "${"+f[0]+"("+f[1]+")}"
# 將舊的值替換成新的值
data_str = data_str.replace(old_value,str(new_value))
return data_str
if __name__ == '__main__':
request_data = {"data1":"${read_yaml(token)}","data2":"${add(1,2)}","data3": "${random()}"}
data_str = yaml.safe_dump(request_data)
print("old_str:%s" % data_str)
data_str = ExtractUtil().hotload_replace(data_str)
print("new_str:%s" % data_str)
打印結(jié)果文章來源:http://www.zghlxwxcb.cn/news/detail-795177.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-795177.html
到了這里,關(guān)于從0開始python學(xué)習(xí)-47.pytest框架之解決Template替換無法進(jìn)行二次處理的問題之熱加載的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!