-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.py
72 lines (61 loc) · 1.88 KB
/
request.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from utils import log
class Request(object):
def __init__(self):
"""
use build method to gain Request Object
"""
self.raw_data = ''
self.method = 'GET'
self.headers = {}
self.path = ''
self.query = {}
self.cookies = {}
self.body = ''
def __repr__(self):
return '\n______ request _______ \n' \
'path {},\nmethod {},\nquery {},\nbody {}\n _____________' \
.format(self.path, self.method, self.query, self.body)
@classmethod
def build(cls, request):
raw = request.decode("utf-8")
r = Request()
r.raw_data = raw
log.d("xxx raw_data is \n" + r.raw_data)
header, r.body = raw.split('\r\n\r\n', 1)
h = header.split('\r\n')
parts = h[0].split()
path = parts[1]
r.method = parts[0]
Request.parse_path(path, r)
Request.add_headers(h[1:], r)
Request.add_cookies(r)
return r
@classmethod
def add_headers(cls, header, request):
lines = header
for line in lines:
k, v = line.split(': ', 1)
request.headers[k] = v
@classmethod
def parse_path(cls, path, request):
index = path.find('?')
if index == -1:
request.path = path
request.query = {}
else:
path, query_string = path.split('?', 1)
args = query_string.split('&')
query = {}
for arg in args:
k, v = arg.split('=')
query[k] = v
request.path = path
request.query = query
@classmethod
def add_cookies(cls, request):
cookies = request.headers.get('Cookie', '')
kvs = cookies.split('; ')
for kv in kvs:
if '=' in kv:
k, v = kv.split('=')
request.cookies[k] = v