学习目标:
读、写yaml文件
yaml文件格式:
提示:请看下方代码!
auth.login:
data:
name: '18888888883'
password: jnyj123456
url: https://XXXX-api-XXXX.zje.com/auth/login
headers:
Accept: '*/*'
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Content-Length: '46'
Content-type: application/json
Host: dexin-api-test.zje.com
Origin: https://XXXX-spa-XXX.zje.com
Referer: https://XXXX-spa-XXX.zje.com/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/98.0.4758.80 Safari/537.36
authorization: Bearer
sec-ch-ua: '" Not A;Brand";v="33"
sec-ch-ua-mobile: ?0000
sec-ch-ua-platform: macOSis
学习产出:
提示:请看下方代码!
class OpenYaml(object):
def __init__(self):
self.file_path = os.path.join(route("/DataYaml/yaml.yaml"))
def open(self, *args):
'''
args[0]: 字典名称
args[1]: 字段值
读取文件
'''
try:
if len(args) == 2:
with open(self.file_path, "r") as f:
Json = f.read()
Dict = yaml.safe_load(Json)[args[0]]
if args[1] in Dict.keys():
logs.info(f"yaml文件,查找内容成功,内容:{Dict[args[1]]}")
return Dict[args[1]]
else:
print(f"对应字段{args[1]}不存在...")
logs.info(f"对应字段{args[1]}不存在...")
elif len(args) > 2:
print("传参超过限时!传入3个以下字段...")
else:
with open(self.file_path, "r") as f:
Json = f.read()
Dict = yaml.safe_load(Json)[args[0]]
return Dict
except Exception as e:
print(f'读取yaml文件,报错:{e}')
logs.info(f'读取yaml文件,报错:{e}')
def Wri_file(self, *args):
'''
:param args: args[0] 接口字段、args[1] key、 args[2] value
:return: None
把字段写入yaml
'''
try:
with open(self.file_path, encoding="utf-8") as f:
data = yaml.load(f.read(), Loader=yaml.FullLoader)
print(data[args[0]])
if data is not None:
if str(data[args[0]][args[1]]) in str(data[args[0]]):
data[args[0]][args[1]] = args[2]
with open(self.file_path, 'w', encoding="utf-8") as f:
yaml.dump(data, stream=f, allow_unicode=True)
else:
print("写入文件的字段不存在!写入失败...")
else:
logs.info("写入文件的返回值为空!不能写入...")
except Exception as y:
logs.info(f"写入文件失败:{y}")
if __name__ == "__main__":
OpenYaml().Wri_file("headers", "Content-Length", "22")
OpenYaml().open("auth.login", "data")
|