1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
|
3
|
|
|
from __future__ import absolute_import |
4
|
|
|
|
5
|
|
|
from benedict.serializers.abstract import AbstractSerializer |
6
|
|
|
from benedict.utils import type_util |
7
|
|
|
|
8
|
|
|
try: |
9
|
|
|
from configparser import ConfigParser |
10
|
|
|
from configparser import DEFAULTSECT as default_section |
11
|
|
|
except ImportError: |
12
|
|
|
from ConfigParser import ConfigParser |
13
|
|
|
default_section = 'DEFAULT' |
14
|
|
|
|
15
|
|
|
from six import PY2, StringIO |
16
|
|
|
|
17
|
|
|
|
18
|
|
|
class INISerializer(AbstractSerializer): |
19
|
|
|
|
20
|
|
|
def __init__(self): |
21
|
|
|
super(INISerializer, self).__init__() |
22
|
|
|
|
23
|
|
|
@staticmethod |
24
|
|
|
def _get_section_option_value(parser, section, option): |
25
|
|
|
value = None |
26
|
|
|
funcs = [ |
27
|
|
|
parser.getint, |
28
|
|
|
parser.getfloat, |
29
|
|
|
parser.getboolean, |
30
|
|
|
parser.get, |
31
|
|
|
] |
32
|
|
|
for func in funcs: |
33
|
|
|
try: |
34
|
|
|
value = func(section, option) |
35
|
|
|
break |
36
|
|
|
except ValueError: |
37
|
|
|
continue |
38
|
|
|
return value |
39
|
|
|
|
40
|
|
|
def decode(self, s, **kwargs): |
41
|
|
|
parser = ConfigParser(**kwargs) |
42
|
|
|
if PY2: |
43
|
|
|
parser.readfp(StringIO(s)) |
44
|
|
|
else: |
45
|
|
|
parser.read_string(s) |
46
|
|
|
data = {} |
47
|
|
|
for option, _ in parser.defaults().items(): |
48
|
|
|
data[option] = self._get_section_option_value( |
49
|
|
|
parser, default_section, option) |
50
|
|
|
for section in parser.sections(): |
51
|
|
|
data[section] = {} |
52
|
|
|
for option, _ in parser.items(section): |
53
|
|
|
data[section][option] = self._get_section_option_value( |
54
|
|
|
parser, section, option) |
55
|
|
|
return data |
56
|
|
|
|
57
|
|
|
def encode(self, d, **kwargs): |
58
|
|
|
parser = ConfigParser(**kwargs) |
59
|
|
|
for key, value in d.items(): |
60
|
|
|
if not type_util.is_dict(value): |
61
|
|
|
parser.set(default_section, key, '{}'.format(value)) |
62
|
|
|
continue |
63
|
|
|
section = key |
64
|
|
|
parser.add_section(section) |
65
|
|
|
for option_key, option_value in value.items(): |
66
|
|
|
parser.set(section, option_key, '{}'.format(option_value)) |
67
|
|
|
str_data = StringIO() |
68
|
|
|
parser.write(str_data) |
69
|
|
|
return str_data.getvalue() |
70
|
|
|
|