34 lines
1.3 KiB
Python
34 lines
1.3 KiB
Python
#tinyWebServer, because microWebSrv wasn't small enough.
|
|
# no decorated route definitions, but whatever
|
|
class tinyWebServer:
|
|
import socket
|
|
_routes={}
|
|
def __init__(self, bind_ip='0.0.0.0', bind_port=80):
|
|
self.bind_ip=bind_ip
|
|
self.bind_port=bind_port
|
|
self.wssock=socket.getaddrinfo(bind_ip, bind_port)[0][-1]
|
|
|
|
def add_route(self, path, handler):
|
|
self._routes.update({b'%s' % path: handler})
|
|
|
|
def start(self):
|
|
self.wss=self.socket.socket()
|
|
self.wss.bind(self.wssock)
|
|
self.wss.listen(1)
|
|
while True: self.handle_request(*self.wss.accept())
|
|
|
|
def handle_request(self, reqclient, reqsocket):
|
|
reqmethod = None
|
|
reqpath = None
|
|
reqclf = reqclient.makefile('rwb', 0)
|
|
while True:
|
|
reqline = reqclf.readline()
|
|
if not reqline or reqline == b'\r\n': break
|
|
if reqmethod == None or reqpath == None and len(reqline.split(' ')) == 3 and reqline.split(' ')[2].startswith('HTTP'):
|
|
reqmethod, reqpath = reqline.split(' ')[:-1]
|
|
if reqmethod == None or reqpath == None: reqclient.close()
|
|
_routes.get(reqpath, self.no_route)(reqclient)
|
|
|
|
def no_route(self, request):
|
|
request.close()
|
|
|