接口测试--Day4
yaml文件介绍和数据读取
一、yaml简介
yaml是一种简洁的非标记语言,yaml以数据为中心,使用空白、缩进、分行组织数据,从而使得更加简洁易读。
由于实现简单解析成本低,yaml特别适合在脚本语言中使用。现有的可以支持yaml的语言有:Ruby、Java、Perl、PHP、JavaScript,Python等。。。。
yaml是专门用来写配置文件的语言,非常简洁强大,远比Jason格式方便。以下是Jason数据和yam数据的一个对比。
Yaml 安装
pip install pyyaml
Json 数据格式:
在Json数据结构里面,键和字符串值必须使用双引号括起来,数据结构的表示使用大括号{}和中括号[]。
{
"name": "LiXiao",
"age": 25,
"spouse": {
"name": "LiHua",
"age": 23
},
"childre": [
{
"name": "Joy",
"age": 6
},
{
"name": "Fun",
"age": 3
}
]
}
yaml 格式:
name: LiXiao
age: 25
spouse:
name: LiHua
age: 23
children:
- name: Joy
age: 6
- name: Fun
age: 3
yaml 语法特点:
- 大小写敏感,
- 使用缩进表示层级关系,
- 缩进时不允许使用table键,只允许使用空格键,
- 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可,
- K值前面带-表示这组数据是一个列表类型,如果两组数据的-属于同级关系的话,数据存在在一个列表里面。
读取yaml数据:
import os.path
import yaml
from interfaceAuto.config.setting import FILE_PATH
def read_yaml(yaml_path):
"""
读取yaml文件数据
:param yaml_path:
:return:
"""
try:
with open(yaml_path, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
return data
except Exception as e:
print(f'读取{yaml_path}文件时出现异常, 原因: {e}')
def write_yaml(value):
"""
yaml 文件数据写入
:param value:
:return:
"""
file_path = FILE_PATH['extract']
if not os.path.exists(file_path):
with open(file_path, 'w'):
pass
file=None
try:
file = open(file_path, 'a', encoding='utf-8')
if isinstance(value, dict):
wrote_data = yaml.dump(value, allow_unicode=True, sort_keys=False)
file.write(wrote_data)
else:
print('写入的数据必须为字典类型!')
except Exception as e:
print(f"写入yaml文件出现异常,原因: {e}")
finally:
file.close()
def clear_yaml():
"""
清空extract.yaml文件
:return:
"""
with open(FILE_PATH['extract'], 'w') as f:
f.truncate()
def get_extract_yaml(node_name, sub_node_name=None):
file_path = FILE_PATH['extract']
try:
with open(file_path,'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
if sub_node_name is None:
return data[node_name]
else:
return data.get(node_name,{}).get(sub_node_name)
except yaml.YAMLError as e:
print(f'error: 读取yaml文件失败,请检查文件格式 {file_path},{e}')
except yaml.YAMLError as e:
print(f'Error: 原因:{e}')

浙公网安备 33010602011771号