Completed
Push — master ( e6e2ec...0ced3f )
by Fabio
01:26
created

benedict.serializers.base64   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 42
dl 0
loc 56
rs 10
c 0
b 0
f 0
wmc 16

3 Methods

Rating   Name   Duplication   Size   Complexity  
B Base64Serializer.decode() 0 18 6
A Base64Serializer.__init__() 0 2 1
C Base64Serializer.encode() 0 15 9
1
# -*- coding: utf-8 -*-
2
3
from benedict.serializers.abstract import AbstractSerializer
4
5
from six import binary_type, string_types
6
7
try:
8
    # python 3
9
    from urllib.parse import unquote
10
except ImportError:
11
    # python 2
12
    from urllib import unquote
13
14
import base64
15
16
17
class Base64Serializer(AbstractSerializer):
18
19
    def __init__(self):
20
        super(Base64Serializer, self).__init__()
21
22
    def decode(self, s, **kwargs):
23
        # fix urlencoded chars
24
        s = unquote(s)
25
        # fix padding
26
        m = len(s) % 4
27
        if m != 0:
28
            s += '=' * (4 - m)
29
        data = base64.b64decode(s)
30
        subformat = kwargs.pop('subformat', None)
31
        encoding = kwargs.pop('encoding', 'utf-8' if subformat else None)
32
        if encoding:
33
            data = data.decode(encoding)
34
            if subformat:
35
                from benedict.serializers import get_serializer_by_format
36
                serializer = get_serializer_by_format(subformat)
37
                if serializer:
38
                    data = serializer.decode(data, **kwargs)
39
        return data
40
41
    def encode(self, d, **kwargs):
42
        data = d
43
        subformat = kwargs.pop('subformat', None)
44
        encoding = kwargs.pop('encoding', 'utf-8' if subformat else None)
45
        if not isinstance(data, string_types) and subformat:
46
            from benedict.serializers import get_serializer_by_format
47
            serializer = get_serializer_by_format(subformat)
48
            if serializer:
49
                data = serializer.encode(data, **kwargs)
50
        if isinstance(data, string_types) and encoding:
51
            data = data.encode(encoding)
52
        data = base64.b64encode(data)
53
        if isinstance(data, binary_type) and encoding:
54
            data = data.decode(encoding)
55
        return data
56