-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
180 lines (153 loc) · 5.22 KB
/
utils.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""
MicroPyServer is a simple HTTP server for MicroPython projects.
@see https://github.com/troublegum/micropyserver
The MIT License
Copyright (c) 2019 troublegum. https://github.com/troublegum/micropyserver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import re
""" HTTP response codes """
HTTP_CODES = {
100: 'Continue',
101: 'Switching protocols',
102: 'Processing',
200: 'Ok',
201: 'Created',
202: 'Accepted',
203: 'Non authoritative information',
204: 'No content',
205: 'Reset content',
206: 'Partial content',
207: 'Multi status',
208: 'Already reported',
226: 'Im used',
300: 'Multiple choices',
301: 'Moved permanently',
302: 'Found',
303: 'See other',
304: 'Not modified',
305: 'Use proxy',
307: 'Temporary redirect',
308: 'Permanent redirect',
400: 'Bad request',
401: 'Unauthorized',
402: 'Payment required',
403: 'Forbidden',
404: 'Not found',
405: 'Method not allowed',
406: 'Not acceptable',
407: 'Proxy authentication required',
408: 'Request timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length required',
412: 'Precondition failed',
413: 'Request entity too large',
414: 'Request uri too long',
415: 'Unsupported media type',
416: 'Request range not satisfiable',
417: 'Expectation failed',
418: 'I am a teapot',
422: 'Unprocessable entity',
423: 'Locked',
424: 'Failed dependency',
426: 'Upgrade required',
428: 'Precondition required',
429: 'Too many requests',
431: 'Request header fields too large',
500: 'Internal server error',
501: 'Not implemented',
502: 'Bad gateway',
503: 'Service unavailable',
504: 'Gateway timeout',
505: 'Http version not supported',
506: 'Variant also negotiates',
507: 'Insufficient storage',
508: 'Loop detected',
510: 'Not extended',
511: 'Network authentication required',
}
def send_response(server, response, http_code=200, content_type="text/html", extend_headers=None):
""" send response """
server.send("HTTP/1.0 " + str(http_code) + " " + HTTP_CODES.get(http_code) + "\r\n")
server.send("Content type:" + content_type + "\r\n")
if extend_headers is not None:
for header in extend_headers:
server.send(header + "\r\n")
server.send("\r\n")
server.send(response)
def get_request_method(request):
""" return http request method """
lines = request.split("\r\n")
return re.search("^([A-Z]+)", lines[0]).group(1)
def get_request_query_string(request):
""" return http request query string """
lines = request.split("\r\n")
match = re.search("\\?(.+)\\s", lines[0])
if match is None:
return ""
else:
return match.group(1)
def parse_query_string(query_string):
""" return params from query string """
if len(query_string) == 0:
return {}
query_params_string = query_string.split("&")
query_params = {}
for param_string in query_params_string:
param = param_string.split("=")
key = param[0]
if len(param) == 1:
value = ""
else:
value = param[1]
query_params[key] = value
return query_params
def get_request_query_params(request):
""" return http request query params """
query_string = get_request_query_string(request)
return parse_query_string(query_string)
def get_request_post_params(request):
""" return params from POST request """
request_method = get_request_method(request)
if request_method != "POST":
return None
match = re.search("\r\n\r\n(.+)", request)
if match is None:
return {}
query_string = match.group(1)
return parse_query_string(query_string)
def unquote(string):
""" unquote string """
if not string:
return ""
if isinstance(string, str):
string = string.encode("utf-8")
bits = string.split(b"%")
if len(bits) == 1:
return string.decode("utf-8")
res = bytearray(bits[0])
append = res.append
extend = res.extend
for item in bits[1:]:
try:
append(int(item[:2], 16))
extend(item[2:])
except KeyError:
append(b"%")
extend(item)
return bytes(res).decode("utf-8")