一、软编码和硬编码
软编码:参数化整个项目配置
硬编码:写死的编码方式
二、ini和ymal文件使用场景
1、xxx.ini:django项目部署uwsgi
2、xxx.ymal:写死的编码方式 dockercompose
3、xxx.py文件 setting.py
4、使用场景:生产环境、测试环境,ip不一样,数据库地址,密码账号不一样
三、ini文件使用和代码编写
1、写法
[section]
key1=val1
key2=val2
key3=val3
类似:字典
{“key1”:“val1”,“key2”:“val2”,“key3”:“val3”}
2、特点
section不可重复
同一个section中key不能重复
等号两边不能有空格
获取值默认是字符串类型
添加、删除、修改只是对缓存区域的
3、使用
获取所有的Section
section=conf.sections()
类似嵌套字典:
test_dict={“testPy1”:{“key1”:“val1”,“key2”:“val2”},“testPy2”:{“key1”:“val1”,“key2”:“val2”}
}
4、编写,在项目中右键新建一个file,命名为:test.ini
[testPy1]
host=192.168.1.20
key2=True
key3=100
[testPy2]
key1=val1
key2=val2
key3=100.9999
Python操作ini文件
from configparser import ConfigParser
conf = ConfigParser()
conf.read(filenames="test.ini", encoding="utf-8")
# 第一种方式
test_sections = conf.sections()
print(test_sections)
conf.keys()
# 第二种方式
test_sections_2 = conf.keys()
print(list(test_sections_2))
# 获取指定sections的key
section1 = conf.options("testPy1")
print(section1) # ['key1', 'key2', 'key3']
# 获取指定section的value 【常用】
val1 = conf.get(section="testPy1", option="host")
print(val1)
# 获取key 和 value
test_options = conf.items(section="testPy1")
print(test_options) # [('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')]
# 获取布尔值
valueBoole = conf.get(section="testPy1",option="key2")
print(valueBoole)
# 获取int类型的值
valueInt = conf.get(section="testPy1",option="key3")
print(valueInt)
# 获取float类型的值
valueFloat = conf.get(section="testPy2",option="key3")
print(valueFloat)
# 其他操作
# 1、添加section操作
conf.add_section(section="your_section")
# 2、添加key、value操作,只是在内存中写入与读取
conf.set("testPy1","k8s","val88")
new_value = conf.get(section="testPy1",option="k8s")
print(new_value)
# 删除操作,也是在内存中
conf.remove_section("testPy1")
简单封装:
from configparser import ConfigParser
class HandleIni:
def __init__(self):
self.conf = ConfigParser()
self.conf.read(filenames="test.ini", encoding="utf-8")
def get_value(self, section, option):
value = self.conf.get(section=section, option=option)
return value
if __name__ == '__main__':
cl = HandleIni()
value = cl.get_value(section="testPy1", option="host")
print(value)
运行结果:192.168.1.20
四、ymal文件使用和代码编写
1、怎么写yaml文件
2、数据类型支持
{key1:val1,key2:[test01,test02,test03]}
3、安装yaml
pip install yaml
4、特点
- 使用缩进来表示层级关系
- 大小写敏感
- 同一个层级的要对其
- 只能用空格,不要用tab
- yaml文件的是一次性读取,不支持连续读取
- 读取出来就是python对象,可以直接取值使用
5、代码实现
在项目中右键新建一个testyaml.yaml文件
key1: value1
key2:
- test01
- test02
- test03
py代码操作yaml文件
import yaml
import os
class HandleYaml:
def __init__(self):
self.file_path = os.path.join(os.path.dirname(__file__), "testyaml.yaml")
def handle_yaml(self):
with open(file=self.file_path, encoding="utf-8") as file:
yaml_value = yaml.load(stream=file, Loader=yaml.FullLoader)
file.close()
return yaml_value
if __name__ == '__main__':
cl = HandleYaml()
value = cl.handle_yaml()
print(value)
运行结果:
{'key1': 'value1', 'key2': ['test01', 'test02', 'test03']}