benedict.serializers.query_string   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 24
dl 0
loc 34
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A QueryStringSerializer.__init__() 0 5 1
A QueryStringSerializer.encode() 0 3 1
A QueryStringSerializer.decode() 0 10 3
1
import re
2
from urllib.parse import parse_qs, urlencode
3
4
from benedict.serializers.abstract import AbstractSerializer
5
6
7
class QueryStringSerializer(AbstractSerializer):
8
    """
9
    This class describes a query-string serializer.
10
    """
11
12
    def __init__(self):
13
        super().__init__(
14
            extensions=[
15
                "qs",
16
                "querystring",
17
            ],
18
        )
19
20
    def decode(self, s, **kwargs):
21
        flat = kwargs.pop("flat", True)
22
        qs_re = r"(?:([\w\-\%\+\.\|]+\=[\w\-\%\+\.\|]*)+(?:[\&]{1})?)+"
23
        qs_pattern = re.compile(qs_re)
24
        if qs_pattern.match(s):
25
            data = parse_qs(s)
26
            if flat:
27
                data = {key: value[0] for key, value in data.items()}
28
            return data
29
        raise ValueError(f"Invalid query string: {s}")
30
31
    def encode(self, d, **kwargs):
32
        data = urlencode(d, **kwargs)
33
        return data
34