一、配置文件分类 软编码:参数化整个项目配置 硬编码:写死的编码方式 1、xxx.ini:django项目部署uwsgi,了解 2.xxx.yaml:java用的多,docker compose,了解 3.xxx.py:python文件,settings.py 4.使用场景:生产环境、测试环境:ip不一样、数据库地址、密码、账号 二、xxx.ini文件 1、写法 [section]:可以自定义 key1=val1 key2=val2 key3=val3 test_dict={'key1': 'val1', 'key2': 'val2', 'key3': 'val3'} print(test_dict['key1']) 2、特点 1、section不能重复 2、同一个section中的key不能重复 3、等号两边不能有空格 4、获取值默认是字符串类型 5、添加、删除、修改只会对缓存区域的改变,不会真实修改文件 3、常用的方法 3.1、获取所有的sections sections = conf.sections() test_sections_2 = conf.keys() 3.2、获取指定的sections下面的所有options test_options =conf.options(section='section') #获取key test_options1 = conf.items(section='section') #获取key,value 3.3、直接获取key(options)的value 3.3.1、value = conf.get(section='section',option='host') # 默认取到的是str【常用】 print(value) 3.3.2、value2= conf.getboolean(section='section',option='key2')布尔值【了解】 print(value2) 3.3.3、value3 = conf.getint(section='section',option='key3')获取数值(int类型),不能写小数,只能写整数【了解】 print(value3) 3.3.4、value4= conf.getfloat(section='section',option='key4')获取数值(float类型)【了解】 print(value4) 4、其他操作 添加 sections(操作内存) conf.add_section('your_section') 添加 key,val(操作内存) conf.set('your_section','key22','val22') 删除(操作内存) conf.remove_option('your_section', "key1") 写入文件 将你内存你的数据全部写入文件进行覆盖,conf 初始化的时候读取的是所有对象 conf.write(fp=open(file=file_path,mode='w'))
# 导入python自带的库
from configparser import ConfigParser
conf = ConfigParser()
conf.read(filenames='testpy42.ini', encoding='utf-8')
# 第一种方式
# sections = conf.sections()
# print(sections)
# 第二种方式
# test_dict = {'testpy1': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'},
# 'testpy2': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
# }
# test_sections_2 = conf.keys()
# print(list(test_sections_2))
# 获取指定sections的key(options)
# 第一种方式
# test_options = conf.options(section='section')
# print(test_options)
# 第二种方式获取key(option),value
# test_options1 = conf.items(section='section')
# print(test_options1)
# 直接获取key(options)的value
value = conf.get(section='section',option='host') # 默认取到的是str
print(value)
# 获取布尔值
value2= conf.getboolean(section='section',option='key2')
print(value2)
# 获取数值(int类型),不能写小数,只能写整数
value3 = conf.getint(section='section',option='key3')
print(value3)
# 获取数值(float类型)
value4= conf.getfloat(section='section',option='key4')
print(value4)
# 其他操作,内存里面进行修改
conf.set('section','k8s','val22')
new_value = conf.get(section='section',option='k8s')
print(new_value)
test_list =[1,2,3,4]
test_list.append(6)
print(test_list)
5、封装
# 封装
from configparser import ConfigParser
class HandleIni:
def __init__(self):
self.conf = ConfigParser()
self.conf.read(filenames='testpy42.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='section', option='host')
print(value)