Completed
Push — master ( 691f67...42518b )
by Fabio
04:47
created

ParseDict.get_uuid()   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nop 4
1
# -*- coding: utf-8 -*-
2
3
from benedict.dicts.base import BaseDict
4
from benedict.dicts.parse import parse_util
5
from benedict.utils import type_util
6
7
from decimal import Decimal
8
9
10
class ParseDict(BaseDict):
11
12
    def __init__(self, *args, **kwargs):
13
        """
14
        Constructs a new instance.
15
        """
16
        super(ParseDict, self).__init__(*args, **kwargs)
17
18
    def _get_value(self, key, default, choices,
19
                   parser_func, parser_kwargs=None):
20
        """
21
        Get value by key, or keypath core method.
22
        If choices and value is in choices return value otherwise default.
23
        """
24
25
        # Get raw value from self.
26
        value = self.get(key, None)
27
        # If value is None return default value.
28
        if value is None:
29
            return default
30
31
        # If not of the desired type, try to parse it using parser_func.
32
        value = parser_func(value, **(parser_kwargs or {}))
33
        # If value is None after parsing return default value.
34
        if value is None:
35
            return default
36
37
        # If choices and value in choices return value otherwise default.
38
        if type_util.is_list_or_tuple(choices) and len(choices) and \
39
                value not in choices:
40
            return default
41
42
        return value
43
44
    def _get_values_list(self, key, default, separator,
45
                         parser_func, parser_kwargs=None):
46
        """
47
        Get value by key or keypath trying to return it as list of bool values.
48
        If separator is specified and value is a string it will be splitted.
49
        """
50
        if key not in self:
51
            return default or []
52
        values_list = self.get_list(key, [], separator)
53
        return [parser_func(value, **(parser_kwargs or {}))
54
                for value in values_list]
55
56
    def get_bool(self, key, default=False):
57
        """
58
        Get value by key or keypath trying to return it as bool.
59
        Values like `1`, `true`, `yes`, `on` will be returned as `True`.
60
        """
61
        return self._get_value(
62
            key, default, [True, False], parse_util.parse_bool)
63
64
    def get_bool_list(self, key, default=None, separator=','):
65
        """
66
        Get value by key or keypath trying to return it as list of bool values.
67
        If separator is specified and value is a string it will be splitted.
68
        """
69
        return self._get_values_list(
70
            key, default, separator, parse_util.parse_bool)
71
72
    def get_datetime(self, key, default=None, format=None, choices=None):
73
        """
74
        Get value by key or keypath trying to return it as datetime.
75
        If format is not specified it will be autodetected.
76
        If choices and value is in choices return value otherwise default.
77
        """
78
        return self._get_value(
79
            key, default, choices, parse_util.parse_datetime,
80
            {'format': format})
81
82
    def get_datetime_list(self, key, default=None, format=None, separator=','):
83
        """
84
        Get value by key or keypath trying to return it as list of datetime values.
85
        If separator is specified and value is a string it will be splitted.
86
        """
87
        return self._get_values_list(
88
            key, default, separator, parse_util.parse_datetime,
89
            {'format': format})
90
91
    def get_decimal(self, key, default=Decimal('0.0'), choices=None):
92
        """
93
        Get value by key or keypath trying to return it as Decimal.
94
        If choices and value is in choices return value otherwise default.
95
        """
96
        return self._get_value(
97
            key, default, choices, parse_util.parse_decimal)
98
99
    def get_decimal_list(self, key, default=None, separator=','):
100
        """
101
        Get value by key or keypath trying to return it as list of Decimal values.
102
        If separator is specified and value is a string it will be splitted.
103
        """
104
        return self._get_values_list(
105
            key, default, separator, parse_util.parse_decimal)
106
107
    def get_dict(self, key, default=None):
108
        """
109
        Get value by key or keypath trying to return it as dict.
110
        If value is a json string it will be automatically decoded.
111
        """
112
        return self._get_value(
113
            key, default or {}, None, parse_util.parse_dict)
114
115
    def get_email(self, key, default='', choices=None, check_blacklist=True):
116
        """
117
        Get email by key or keypath and return it.
118
        If value is blacklisted it will be automatically ignored.
119
        If check_blacklist is False, it will be not ignored even if blacklisted.
120
        """
121
        return self._get_value(
122
            key, default, choices, parse_util.parse_email,
123
            {'check_blacklist': check_blacklist})
124
125
    def get_float(self, key, default=0.0, choices=None):
126
        """
127
        Get value by key or keypath trying to return it as float.
128
        If choices and value is in choices return value otherwise default.
129
        """
130
        return self._get_value(
131
            key, default, choices, parse_util.parse_float)
132
133
    def get_float_list(self, key, default=None, separator=','):
134
        """
135
        Get value by key or keypath trying to return it as list of float values.
136
        If separator is specified and value is a string it will be splitted.
137
        """
138
        return self._get_values_list(
139
            key, default, separator, parse_util.parse_float)
140
141
    def get_int(self, key, default=0, choices=None):
142
        """
143
        Get value by key or keypath trying to return it as int.
144
        If choices and value is in choices return value otherwise default.
145
        """
146
        return self._get_value(
147
            key, default, choices, parse_util.parse_int)
148
149
    def get_int_list(self, key, default=None, separator=','):
150
        """
151
        Get value by key or keypath trying to return it as list of int values.
152
        If separator is specified and value is a string it will be splitted.
153
        """
154
        return self._get_values_list(
155
            key, default, separator, parse_util.parse_int)
156
157
    def get_list(self, key, default=None, separator=','):
158
        """
159
        Get value by key or keypath trying to return it as list.
160
        If separator is specified and value is a string it will be splitted.
161
        """
162
        return self._get_value(
163
            key, default or [], None, parse_util.parse_list,
164
            {'separator': separator})
165
166
    def get_list_item(self, key, index=0, default=None, separator=','):
167
        """
168
        Get list by key or keypath and return value at the specified index.
169
        If separator is specified and list value is a string it will be splitted.
170
        """
171
        values = self.get_list(key, None, separator)
172
        if values:
173
            try:
174
                value = values[index]
175
                return value
176
            except IndexError:
177
                return default
178
        else:
179
            return default
180
181
    def get_phonenumber(self, key, country_code=None, default=None):
182
        """
183
        Get phonenumber by key or keypath and return a dict
184
        with different formats (e164, international, national).
185
        If country code is specified (alpha 2 code),
186
        it will be used to parse phone number correctly.
187
        """
188
        return self._get_value(
189
            key, default or {}, None, parse_util.parse_phonenumber,
190
            {'country_code': country_code})
191
192
    def get_slug(self, key, default='', choices=None):
193
        """
194
        Get value by key or keypath trying to return it as slug.
195
        If choices and value is in choices return value otherwise default.
196
        """
197
        return self._get_value(
198
            key, default, choices, parse_util.parse_slug)
199
200
    def get_slug_list(self, key, default=None, separator=','):
201
        """
202
        Get value by key or keypath trying to return it as list of slug values.
203
        If separator is specified and value is a string it will be splitted.
204
        """
205
        return self._get_values_list(
206
            key, default, separator, parse_util.parse_slug)
207
208
    def get_str(self, key, default='', choices=None):
209
        """
210
        Get value by key or keypath trying to return it as string.
211
        Encoding issues will be automatically fixed.
212
        If choices and value is in choices return value otherwise default.
213
        """
214
        return self._get_value(
215
            key, default, choices, parse_util.parse_str)
216
217
    def get_str_list(self, key, default=None, separator=','):
218
        """
219
        Get value by key or keypath trying to return it as list of str values.
220
        If separator is specified and value is a string it will be splitted.
221
        """
222
        return self._get_values_list(
223
            key, default, separator, parse_util.parse_str)
224
225
    def get_uuid(self, key, default='', choices=None):
226
        """
227
        Get value by key or keypath trying to return it as valid uuid.
228
        If choices and value is in choices return value otherwise default.
229
        """
230
        return self._get_value(
231
            key, default, choices, parse_util.parse_uuid)
232
233
    def get_uuid_list(self, key, default=None, separator=','):
234
        """
235
        Get value by key or keypath trying to return it as list of valid uuid values.
236
        If separator is specified and value is a string it will be splitted.
237
        """
238
        return self._get_values_list(
239
            key, default, separator, parse_util.parse_uuid)
240