2020-01-20 15:19:53 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
import re
|
2022-10-14 14:53:06 +00:00
|
|
|
from urllib.parse import parse_qs, urlencode
|
|
|
|
|
|
|
|
from benedict.serializers.abstract import AbstractSerializer
|
2020-01-20 15:19:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
class QueryStringSerializer(AbstractSerializer):
|
2022-02-13 10:56:44 +00:00
|
|
|
"""
|
|
|
|
This class describes a query-string serializer.
|
|
|
|
"""
|
|
|
|
|
2020-02-20 16:14:48 +00:00
|
|
|
def __init__(self):
|
2022-10-05 14:43:46 +00:00
|
|
|
super(QueryStringSerializer, self).__init__(
|
|
|
|
extensions=[
|
|
|
|
"qs",
|
|
|
|
"querystring",
|
|
|
|
],
|
|
|
|
)
|
2020-02-20 16:14:48 +00:00
|
|
|
|
|
|
|
def decode(self, s, **kwargs):
|
2022-02-13 10:35:43 +00:00
|
|
|
flat = kwargs.pop("flat", True)
|
|
|
|
qs_re = r"(?:([\w\-\%\+\.\|]+\=[\w\-\%\+\.\|]*)+(?:[\&]{1})?)+"
|
2020-01-20 15:19:53 +00:00
|
|
|
qs_pattern = re.compile(qs_re)
|
|
|
|
if qs_pattern.match(s):
|
|
|
|
data = parse_qs(s)
|
|
|
|
if flat:
|
|
|
|
data = {key: value[0] for key, value in data.items()}
|
|
|
|
return data
|
2022-02-18 00:02:02 +00:00
|
|
|
raise ValueError(f"Invalid query string: {s}")
|
2020-01-20 15:19:53 +00:00
|
|
|
|
2020-02-20 16:14:48 +00:00
|
|
|
def encode(self, d, **kwargs):
|
2020-01-20 15:19:53 +00:00
|
|
|
data = urlencode(d, **kwargs)
|
|
|
|
return data
|