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
|
|
|
|