Passed
Push — master ( e9e603...c36ccf )
by dai
04:57
created

school_api.utils   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 53
rs 10
c 0
b 0
f 0
wmc 12

3 Methods

Rating   Name   Duplication   Size   Complexity  
A ObjectDict.__getstate__() 0 2 1
A ObjectDict.__getattr__() 0 4 2
A ObjectDict.__setattr__() 0 2 1

2 Functions

Rating   Name   Duplication   Size   Complexity  
A to_binary() 0 13 4
A to_text() 0 14 4
1
# -*- coding: utf-8 -*-
2
3
from __future__ import absolute_import, unicode_literals
4
import six
5
6
7
class ObjectDict(dict):
8
    """:copyright: (c) 2014 by messense.
9
    Makes a dictionary behave like an object, with attribute-style access.
10
    """
11
12
    def __getattr__(self, key):
13
        if key in self:
14
            return self[key]
15
        return None
16
17
    def __setattr__(self, key, value):
18
        self[key] = value
19
20
    def __getstate__(self):
21
        return None
22
23
24
def to_text(value, encoding='utf-8'):
25
    """:copyright: (c) 2014 by messense.
26
    Convert value to unicode, default encoding is utf-8
27
28
    :param value: Value to be converted
29
    :param encoding: Desired encoding
30
    """
31
    if not value:
32
        return ''
33
    if isinstance(value, six.text_type):
34
        return value
35
    if isinstance(value, six.binary_type):
36
        return value.decode(encoding)
37
    return six.text_type(value)
38
39
40
def to_binary(value, encoding='utf-8'):
41
    """Convert value to binary string, default encoding is utf-8
42
43
    :param value: Value to be converted
44
    :param encoding: Desired encoding
45
    """
46
    if not value:
47
        return b''
48
    if isinstance(value, six.binary_type):
49
        return value
50
    if isinstance(value, six.text_type):
51
        return value.encode(encoding)
52
    return to_text(value).encode(encoding)
53