From 6728d0093a78253584bc3ee3336e41ca73b3dcce Mon Sep 17 00:00:00 2001 From: Tom Date: Fri, 22 May 2020 19:29:13 -0700 Subject: [PATCH] finished activity --- simple_web_server/main.py | 42 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/simple_web_server/main.py b/simple_web_server/main.py index b860471..6625fc5 100644 --- a/simple_web_server/main.py +++ b/simple_web_server/main.py @@ -3,10 +3,21 @@ except: import socket +response_404 = """HTTP/1.0 404 NOT FOUND + +

404 Not Found

+""" + +response_500 = """HTTP/1.0 500 INTERNAL SERVER ERROR + +

500 Internal Server Error

+""" + response_template = """HTTP/1.0 200 OK %s """ + import machine import ntptime, utime from machine import RTC @@ -30,6 +41,25 @@ def time(): return response_template % body +def dummy(): + body = "This is a dummy endpoint" + + return response_template % body + +switch_pin = machine.Pin(10, machine.Pin.IN) + +def switch(): + body = "{state: " . switch_pin.value() . "}" + return response_template % body + +handlers = { + 'time': time, + 'dummy': dummy, + 'light_on': light_on, + 'light_off': light_off, + 'switch': switch, +} + def main(): s = socket.socket() ai = socket.getaddrinfo("0.0.0.0", 8080) @@ -49,8 +79,16 @@ def main(): req = client_s.recv(4096) print("Request:") print(req) - - response = time() + + try: + path = req.decore().split("\r\n")[0].split(" ")[1] + handler = handlers[path.strip('/').split('/')[0]] + response = handler() + except KeyError: + response = response_404 + except Exception as e: + response = response_500 + print(str(e)) client_s.send(b"\r\n".join([line.encode() for line in response.split("\n")]))