一 Yaml简介
1.yaml [ˈjæməl]: Yet Another Markup Language :
另一种标记语言。yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文件,看了yaml后,发现这个更直观,更方便,有点类似于json格式
2.yaml基本语法规则:
大小写敏感
使用缩进表示层级关系
缩进时不允许使用Tab键,只允许使用空格。
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
#表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样
3.yaml支持的数据结构有三种:
对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期
字典如下:
#python
"data":
{
“user”: "admin",
"pasword": "123456"
}
# yaml
data:
user: admin
password: 123456
list如下
#python
[{'admin1': 123456}, {'admin2': 111111}, {'admin3': 222222}]
#yaml
- admin1: 123456
- admin2: 111111
- admin3: 222222
纯量如下:
yaml python
n1:12.30 n1=12.3
n2: true n2=True
n3: false n3=False
n4: ~ n4=None
4.使用pip安装pyyaml模块:
pip install pyyaml
二 python读取yaml文件
yaml文件示例:
- desc: 正常登录
url: http://ip:auth/oauth/token
headers:
Authorization: Basic cGlnOnBpZw==
method: post
datail: 正常登录
data:
username: admin
password: lucy
grant_type: password
- desc: 密码错误
url: http://ip:auth/oauth/token
headers:
Authorization: Basic cGlnOnBpZw==
method: post
datail: 密码错误
data:
username: admin
password: 123456
grant_type: password
python文件示例
import yaml
import requests
with open('data.yaml','r',encoding='utf-8') as f:
file_content=f.read()
contet=yaml.load(file_content,yaml.FullLoader)
for item1 in contet:
data=item1['data']
url=item1['url']
headers=item1['headers']
if item1['method']=="get":
response=requests.get(url=url,data=data,headers=headers)
print(response.text)
else:
response=requests.post(url=url,data=data,headers=headers)
print(response.text)
输出结果如下:
{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsaWNlbnNlIjoibWFkZSBieSBob25nZGlhbjE1OTI3IiwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJzZXJ2ZXIiXSwiZXhwIjoxNTk4ODcwNzY2LCJ1c2VySWQiOjEsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiXSwianRpIjoiMGI5MTU0MzMtM2M2Mi00M2NkLWI1NWQtMmI4OWYxNTQ1ZmM2IiwiY2xpZW50X2lkIjoicGlnIn0.qlLu9QmTVZ2Ss53hQ1DcAa9rpmCELLAIfHyO6vAKJ-g","token_type":"bearer","refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsaWNlbnNlIjoibWFkZSBieSBob25nZGlhbjE1OTI3IiwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJzZXJ2ZXIiXSwiYXRpIjoiMGI5MTU0MzMtM2M2Mi00M2NkLWI1NWQtMmI4OWYxNTQ1ZmM2IiwiZXhwIjoxNjAxNDMzOTY2LCJ1c2VySWQiOjEsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiXSwianRpIjoiNDRmYWU3ODUtZWQzZS00ZGRlLTkwZTktNmM5MDZmYzAxYzNkIiwiY2xpZW50X2lkIjoicGlnIn0.u57tUCzMLcwR5MfOTDyQ2xcjzpV-J4fFoHHiExUlOxk","expires_in":28799,"scope":"server","license":"made by hongdian15927","userId":1,"jti":"0b915433-3c62-43cd-b55d-2b89f1545fc6"} {"error":"invalid_grant","error_description":"用户名不存在或者密码错误"}
网友评论