前言:引用渲染变量的模板有2个,一个是字符串模板,另一个是Jinja2模板
1. 字符串模板
1.1.1 通过字符串格式化方法进行渲染需要渲染的变量:
name = "dack"
age = 23
x = 'my name is %s, my age is %d' % (name, age)
print(x)
y = "my name is {}, my age is {}".format(name, age)
print(y)
z = f"my name is {name}, my age is {age}"
print(z)
1.1.2 template字符串模板
template 是字符串模板,用于替换字符串中的变量,是 string 的一个类引用变量有 2 种格式
$variable
使用 $变量名 引用变量${variable}
使用 ${变量名} 大括号包起来
# 第一种:$variable
from string import Template
tempTemplate_1 = Template("My name is $name, I like $fancy")
d = {"name": "dack", "fancy": "Python"}
print(tempTemplate_1.substitute(d))
# 结果: my name is dack, my age is 23
# 第二种:${variable}
tempTemplate_2 = Template("My name is ${name}, I like ${fancy}")
c = {"name": "dack", "fancy": "Python"}
print(tempTemplate_2.substitute(c))
# 结果: my name is dack, my age is 23
"""============================================================================"""
# 上面的方式只能严格的匹配变量,当字符串中有 $ 符号,不想匹配变量的时候,会报错
# safe_substitute 使用
from string import Template
tempTemplate_3 = Template("$My name is ${name}, I like ${fancy}")
e = {"name": "dack", "fancy": "Python"}
print(tempTemplate_3.substitute(e))
# 结果:error: KeyError: 'My'
# 忽略上面的error,使用Template里的safe_substitute方法,可以忽略匹配不到的变量
print(tempTemplate_3.safe_substitute(e))
# 结果:$My name is dack, I like Python
# 虽然字符串定义了多个变量,但是引用的时候只给了name这个值,也不影响运行,没给值的当普通字符串出来,这样就很完美了
1.1 yaml文件引用变量
test_login:
name: 登录成功
request:
url: /api/v1/auth/login
method: POST
json:
username: ${username}
password: ${password}
test_login2:
name: 登录失败
request:
url: /api/v1/auth/login
method: POST
json:
username: "admin"
password: "Admin@2233"
修改读取yaml文件的代码块:
# utils/read_file.py
import yaml
from string import Template
from pathlib import Path
def read_yaml(file_path: Path):
"""
读取 yaml 数据,转 python 类型
:param file_path:
:return: dict
"""
with open(file_path, 'r', encoding='utf-8') as fp:
read_yml_data = fp.read() # 读到的是字符串
temTemplate = Template(read_yml_data)
yaml_data = temTemplate.safe_substitute({"username": "admin", "password": "Admin@22"})
# str 转 python dict
yaml_data = yaml.safe_load(yaml_data)
return yaml_data
if __name__ == '__main__':
file_path = Path(__file__).parent.parent.joinpath('data', 'login.yml')
res = read_yaml(file_path)
print(res)
print(type(res)) # -->dict
运行结果: