-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
49 lines (40 loc) · 1.3 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""Utility"""
import re
from json import loads
from urllib.parse import urlencode
from django.http import QueryDict
class RequestBodyDecoder:
"""Request Body Decoder"""
def __init__(self, body: bytes, default=QueryDict(urlencode({}))):
self.body = body
self.default = default
def decode(self) -> QueryDict:
"""decode to QueryDict"""
if not self.body:
return self.default
decode_methods = ("normal", "regex")
for method in decode_methods:
data = getattr(self, method)(self.body)
if data:
return self.to_query_dict(data)
return self.default
@staticmethod
def to_query_dict(data: dict) -> QueryDict:
"""dict to QueryDict"""
return QueryDict(urlencode(data))
@staticmethod
def normal(body: bytes) -> dict:
"""json decode"""
try:
return loads(body)
except ValueError:
return {}
@staticmethod
def regex(body: bytes) -> dict:
"""regex decode"""
data = {}
pattern = rb'name="(?P<name>.+)"\r\n\r\n(?P<value>.+)\r\n'
for match in re.finditer(pattern, body):
name, value = match.group("name"), match.group("value")
data[name.decode()] = value.decode()
return data