uPyLibs/uPyhttpd.py

57 lines
2.1 KiB
Python

#tinyWebServer, because microWebSrv wasn't small enough.
import socket
_routes={}
_HTTPStatusCodes={
100: 'Continue',
101: 'Switching Protocols',
200: 'OK',
201: 'Created',
202: 'Accepted',
204: 'No Content',
301: 'Moved Permanently',
302: 'Found',
404: 'Not Found',
500: 'Not Implemented',
}
def __init__(self, bind_ip='0.0.0.0', bind_port=80, verbose=False):
self.verbose=verbose
self.bind_ip=bind_ip
self.bind_port=bind_port
self.wssock=self.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)
print("tinyWebServer started on %s:%d" % (self.bind_ip, self.bind_port))
while True: self.handle_request(*self.wss.accept())
def handle_request(self, reqclient, reqsocket):
if reqclient == None or reqsocket == None: return
if self.verbose: print(reqclient)
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 reqline.find(b' ') >= 0 and len(reqline.split(b' ')) == 3 and reqline.split(b' ')[2].startswith(b'HTTP'):
reqmethod, reqpath = reqline.split(b' ')[:-1]
if reqmethod == None or reqpath == None:
if self.verbose: print("closing attempted keepalive")
reqclient.close()
return
if self.verbose: print("client connected from %s: %s %s" % (reqsocket[0], reqmethod, reqpath))
reqclient.send(self._routes.get(reqpath, self.no_route)(reqclient))
reqclient.close()
def respond(self, body='', status=200, ctype="application/json"):
return "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nConnection: close\r\nServer: tinyWebServer (horny)\r\n\r\n%s" % (
status, self._HTTPStatusCodes[status], ctype, body)
def no_route(self, request):
return self.respond(status=404)