python-benedict/benedict/serializers/ini.py

62 lines
1.9 KiB
Python
Raw Normal View History

from configparser import DEFAULTSECT as default_section
from configparser import ConfigParser
from io import StringIO
2021-05-04 21:22:11 +00:00
from benedict.serializers.abstract import AbstractSerializer
from benedict.utils import type_util
2021-05-04 21:22:11 +00:00
class INISerializer(AbstractSerializer):
2022-02-13 10:56:44 +00:00
"""
This class describes an ini serializer.
"""
2021-05-04 21:22:11 +00:00
def __init__(self):
super().__init__(
extensions=[
"ini",
],
)
2021-05-04 21:22:11 +00:00
@staticmethod
def _get_section_option_value(parser, section, option):
value = None
2021-10-12 12:27:35 +00:00
funcs = [parser.getint, parser.getfloat, parser.getboolean, parser.get]
2021-05-04 21:22:11 +00:00
for func in funcs:
try:
value = func(section, option)
break
except ValueError:
continue
return value
def decode(self, s, **kwargs):
parser = ConfigParser(**kwargs)
parser.read_string(s)
2021-05-04 21:22:11 +00:00
data = {}
for option, _ in parser.defaults().items():
data[option] = self._get_section_option_value(
2021-10-12 12:27:35 +00:00
parser, default_section, option
)
2021-05-04 21:22:11 +00:00
for section in parser.sections():
data[section] = {}
for option, _ in parser.items(section):
data[section][option] = self._get_section_option_value(
2021-10-12 12:27:35 +00:00
parser, section, option
)
2021-05-04 21:22:11 +00:00
return data
def encode(self, d, **kwargs):
parser = ConfigParser(**kwargs)
for key, value in d.items():
if not type_util.is_dict(value):
parser.set(default_section, key, f"{value}")
2021-05-04 21:22:11 +00:00
continue
section = key
parser.add_section(section)
for option_key, option_value in value.items():
parser.set(section, option_key, f"{option_value}")
2021-05-04 21:22:11 +00:00
str_data = StringIO()
parser.write(str_data)
return str_data.getvalue()