-
Notifications
You must be signed in to change notification settings - Fork 33
/
micropyserver.py
154 lines (132 loc) · 5.33 KB
/
micropyserver.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
"""
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 NONINFRINGEMENT. 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
import socket
import sys
import io
class MicroPyServer(object):
def __init__(self, host="0.0.0.0", port=80):
""" Constructor """
self._host = host
self._port = port
self._routes = []
self._connect = None
self._on_request_handler = None
self._on_not_found_handler = None
self._on_error_handler = None
self._sock = None
def start(self):
""" Start server """
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._sock.bind((self._host, self._port))
self._sock.listen(1)
print("Server start")
while True:
if self._sock is None:
break
try:
self._connect, address = self._sock.accept()
request = self.get_request()
if len(request) == 0:
self._connect.close()
continue
if self._on_request_handler:
if not self._on_request_handler(request, address):
continue
route = self.find_route(request)
if route:
route["handler"](request)
else:
self._route_not_found(request)
except Exception as e:
self._internal_error(e)
finally:
self._connect.close()
def stop(self):
""" Stop the server """
self._connect.close()
self._sock.close()
self._sock = None
print("Server stop")
def add_route(self, path, handler, method="GET"):
""" Add new route """
self._routes.append(
{"path": path, "handler": handler, "method": method})
def send(self, data):
""" Send data to client """
if self._connect is None:
raise Exception("Can't send response, no connection instance")
self._connect.sendall(data.encode())
def find_route(self, request):
""" Find route """
lines = request.split("\r\n")
method = re.search("^([A-Z]+)", lines[0]).group(1)
path = re.search("^[A-Z]+\\s+(/[-a-zA-Z0-9_.]*)", lines[0]).group(1)
for route in self._routes:
if method != route["method"]:
continue
if path == route["path"]:
return route
else:
match = re.search("^" + route["path"] + "$", path)
if match:
print(method, path, route["path"])
return route
def get_request(self, buffer_length=4096):
""" Return request body """
return str(self._connect.recv(buffer_length), "utf8")
def on_request(self, handler):
""" Set request handler """
self._on_request_handler = handler
def on_not_found(self, handler):
""" Set not found handler """
self._on_not_found_handler = handler
def on_error(self, handler):
""" Set error handler """
self._on_error_handler = handler
def _route_not_found(self, request):
""" Route not found handler """
if self._on_not_found_handler:
self._on_not_found_handler(request)
else:
""" Default not found handler """
self.send("HTTP/1.0 404 Not Found\r\n")
self.send("Content-Type: text/plain\r\n\r\n")
self.send("Not found")
def _internal_error(self, error):
""" Internal error handler """
if self._on_error_handler:
self._on_error_handler(error)
else:
""" Default internal error handler """
if "print_exception" in dir(sys):
output = io.StringIO()
sys.print_exception(error, output)
str_error = output.getvalue()
output.close()
else:
str_error = str(error)
self.send("HTTP/1.0 500 Internal Server Error\r\n")
self.send("Content-Type: text/plain\r\n\r\n")
self.send("Error: " + str_error)
print(str_error)