• python之读取yaml数据


    一、yaml简介

    yaml:一种标记语言,专门用来写配置文件。

    二、yaml基础语法

    • 区分大小写;
    • 使用缩进表示层级关系;
    • 使用空格键缩进,而非Tab键缩进
    • 缩进的空格数目不固定,只需要相同层级的元素左侧对齐;
    • 文件中的字符串不需要使用引号标注,但若字符串包含有特殊字符则需用引号标注;
    • 注释标识为#

    三、yaml的数据结构

    • 对象:键值对的集合(简称 "映射或字典")
      键值对用冒号 “:” 结构表示,冒号与值之间需用空格分隔
    • 数组:一组按序排列的值(简称 "序列或列表")
      数组前加有 “-” 符号,符号与值之间需用空格分隔
    • 纯量(scalars):单个的、不可再分的值(如:字符串、bool值、整数、浮点数、时间、日期、null等)
      None值可用null可 ~ 表示
     
    四、使用python读取yaml常见的数据结构

    前提:python中读取yaml文件前需要安装pyyaml和导入yaml模块。

    python读取yaml:

    # get_yaml.py
    
    import yaml
    
    def get_yaml_data(yaml_file):
        print("*****获取yaml数据*****")
        with open(yaml_file, encoding='utf-8')as file:
            content = file.read()
            print(content)
            print(type(content))
    
            print("
    *****转换yaml数据为字典或列表*****")
            # 设置Loader=yaml.FullLoader忽略YAMLLoadWarning警告
            data = yaml.load(content, Loader=yaml.FullLoader)
            print(data)
            print(type(data))
            print(data.get('my'))  # 类型为字典 <class 'dict'>
        # print(data[0]["model"]) # 若类型为列表 <class 'list'>
    if __name__ == "__main__":
        get_yaml_data("config.yaml")
     
    1、yaml键值对:即python中的字典
    # config.yaml
    user: my
    pwd: 1111

    运行结果:

    *****获取yaml数据*****
    # yaml键值对:即python中的字典
    user: my
    pwd: 1111
    <class 'str'> *****转换yaml数据为字典或列表***** {'user': 'my', 'pwd': 1111} <class 'dict'> my

    2、yaml键值对嵌套:即python中的字典嵌套字典

    # config.yaml
    
    user1:
      name: a
      pwd: 111222
    user2:
      name: b
      pwd: 222333

    运行结果:

    *****获取yaml数据*****
    user1:
      name: a
      pwd: 111222
    user2:
      name: b
      pwd: 222333
    <class 'str'>
    
    *****转换yaml数据为字典或列表*****
    {'user1': {'name': 'a', 'pwd': 111222}, 'user2': {'name': 'b', 'pwd': 222333}}
    <class 'dict'>
    {'name': 'a', 'pwd': 111222}

    3、yaml键值对中嵌套数组

    # config.yaml
    
    user3:
      - a
      - b
    user4:
      - d
      - e

    运行结果:

    *****获取yaml数据*****
    user3:
      - a
      - b
    user4:
      - d
      - e
    <class 'str'>
    
    *****转换yaml数据为字典或列表*****
    {'user3': ['a', 'b'], 'user4': ['d', 'e']}
    <class 'dict'>
    ['a', 'b']

    4、yaml数组中嵌套键值对

    # config.yaml
    
    - user1: aaa
    - pwd1: 111
      user2: bbb
      pwd2: 222

    运行结果:

    *****获取yaml数据*****
    - user1: aaa
    - pwd1: 111
      user2: bbb
      pwd2: 222
    <class 'str'>
    
    *****转换yaml数据为字典或列表*****
    [{'user1': 'aaa'}, {'pwd1': 111, 'user2': 'bbb', 'pwd2': 222}]
    <class 'list'>  # 注意,此时的类型为list而非dict, 所以用下标访问,即data[0]["user1"]
    aaa

    5、yaml中纯量

    # config.yaml
    
    s_val: hello world
    num_val: 15
    bol_val: true
    nul_val: null
    data_val: 2020-08-17

    运行结果:

    *****获取yaml数据*****
    s_val: hello world
    num_val: 15
    bol_val: true
    nul_val: null
    data_val: 2020-08-17
    <class 'str'>
    
    *****转换yaml数据为字典或列表*****
    {'s_val': 'hello world', 'num_val': 15, 'bol_val': True, 'nul_val': None, 'data_val': datetime.date(2020, 8, 17)}
    <class 'dict'>
    hello world
     案例实践:
    # config.yaml
    
    # 使用-分隔用例,则yaml读取到的数据类型为列表
    -
      model: 注册模块
      title: 注册成功
      url: http://api.nnzhp.cn/api/user/user_reg
      method: POST
      data:
        username: yingcr8
        pwd: Ace123456
        cpwd: Ace123456
      check:
        error_code: 0
        msg: 注册成功!
    -
      model: 注册模块
      title: 用户名长度小于6位,注册失败
      url: http://api.nnzhp.cn/api/user/user_reg
      method: POST
      data:
        username: yingc
        pwd: Ace123456
        cpwd: Ace123456
      check:
        error_code: 3002
    # get_yaml.py
    
    import requests
    import yaml
    import urllib3
    import json
    urllib3.disable_warnings()
    
    class SignTest():
    
        def __init__(self, file):
            self.file = file
    
        def test_sign(self):
            with open(self.file, encoding='utf-8') as fobj:
                content = fobj.read()
           # 使用 yaml.load()将yaml数据转换为list或dict data
    = yaml.load(content, Loader=yaml.FullLoader)
           # 使用for循环,依次读取测试用例
    for i in range(len(data)): # 从config.yaml中提取接口的参数
           # 由于读取到的数据类型为list列表,所以只能用下标访问
    model = data[i]['model'] title = data[i]['title'] url = data[i]['url'] method = data[i]['method'] datas = data[i]['data'] check = data[i]['check'] self.sign_test(model, title, url, method, datas, check) def sign_test(self, model, title, url, method, datas, check): print("模块:", model) print("用例标题:", title) response = requests.request(url=url, method=method, data=datas) response = json.loads(response.text) print(response) try: # 通过断言,判断实际结果是否与预期结果一致 assert check['error_code'] == response['error_code'] print("测试通过 ") except Exception: print("测试失败 ") if __name__ == "__main__": signtest = SignTest("config.yaml") signtest.test_sign()

    运行结果:

    模块: 注册模块
    用例标题: 注册成功
    {'error_code': 0, 'msg': '注册成功!'}
    测试通过
    
    模块: 注册模块
    用例标题: 用户名长度小于6位,注册失败
    {'error_code': 3002, 'msg': '用户名长度为6-10位!'}
    测试通过
     

    参考:https://www.jianshu.com/p/eaa1bf01b3a6

  • 相关阅读:
    「CSP模拟」模拟测试6
    「CSP模拟」模拟测试5
    镇黑板
    求和「Dirichlet 前缀和」
    二叉搜索树「区间DP」
    序列
    [CSP模拟]异或帽子+传话游戏+全球覆盖+幂次序列
    MySQL常用引擎及优缺点
    Django项目远程开发环境搭建
    MySQL8.0安装与配置
  • 原文地址:https://www.cnblogs.com/Maruying/p/13516789.html
Copyright © 2020-2023  润新知