HTTP请求参数解析器实现

HTTP请求参数

  • GET / DELETE 查询参数/URL参数
  • POST / PATCH / PUT
    • 请求体(body)application/json www-xxxx form-data
    • request.POST {“key”: “123”}

解析器实现目标

  • 能解析GET/POST参数
  • 参数校验
    • 参数类型,例如必需是int
    • 必填判断
    • 自定义校验,例如该参数只是能(“a”, “b”, “c”)中的一个

代码实现

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import json

body = {
"id": "12",
"url": "https://gitee.com/yooke/User.git",
"type": "c",
}

# request.GET
# request.POST
# application/json json.loads(request.body)


body = json.dumps(body)


class Argument:
def __init__(self, key, required=True, filter=None, type=None, help=None):
self.key = key
self.required = required
self.filter = filter
self.type = type
self.help = help


class Parser:
def __init__(self, *arguments):
self.arguments = arguments

def parse(self, data):
form, error = {}, None
for arg in self.arguments:
value = data.get(arg.key)
if arg.required and value is None: # 判断required属性是否必填
error = arg.help
break
if arg.type: # 判断type属性类型是否正确
if not isinstance(value, arg.type):
try:
value = arg.type(value) # 尝试转换类型
except ValueError:
error = arg.help
break
if arg.filter and not arg.filter(value): # 判断是否符合filter过滤条件
error = arg.help
break
form[arg.key] = value
return form, error


class JSONParser(Parser): # 扩展解析JSON消息体
def parse(self, data):
data = json.loads(data)
return super().parse(data)


class XMLParser(Parser): # 扩展解析XML消息体
def xmltodict(self, data):
# TODO: xml to dict
return data

def parse(self, data):
data = self.xmltodict(data)
return super().parse(data)


def main():
form, error = JSONParser(
Argument('id', type=int, help='ID必须是整数'),
Argument('name', required=False, help='name参数必填'),
Argument('url', help='url参数必填'),
Argument('type', filter=lambda x: x in ('a', 'b', 'c'), help='type参数必须是a,b,c中的一个'),
).parse(body)
if error is None:
print('参数校验通过: ', form)
else:
print('参数校验失败: ', error)


main()