1. 程式人生 > 實用技巧 >python之讀取yaml資料

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("\n*****轉換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("測試通過\n") except Exception: print("測試失敗\n") 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