diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 index c239a80..0f92536 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.DS_Store # Project files uWeb/* !uWeb/404.html @@ -6,7 +7,7 @@ uWeb/* !uWeb/layout.html !uWeb/uWeb.py !uWeb/uWeb_uasyncio.py - +main.py ### VisualStudioCode ### .vscode/ diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 8be979c..b0ba6d0 --- a/README.md +++ b/README.md @@ -12,8 +12,8 @@ - [μWeb vs. μWeb-uasyncio](#%ce%bcweb-vs-%ce%bcweb-uasyncio) - [Installation](#installation) - [Quick Start](#quick-start) - - [Example application using μWeb](#example-application-using-%ce%bcweb) - - [Example application using μWeb-uasyncio](#example-application-using-%ce%bcweb-uasyncio) + - [Example application using μWeb](#example-application-using-%ce%bcweb) + - [Example application using μWeb-uasyncio](#example-application-using-%ce%bcweb-uasyncio) - [Using uWeb-uasyncio](#using-uweb-uasyncio) - [Template Rendering](#template-rendering) - [Layout Rendering](#layout-rendering) @@ -96,88 +96,100 @@ You can run uWeb with the MicroPython unix port ```python from uWeb import uWeb, loadJSON -server = uWeb("0.0.0.0", 8000) #init uWeb object +server = uWeb("0.0.0.0", 8000) # init uWeb object -def home(): #render HTML page - vars = { - 'name': 'MicroPython', - 'answer': (1+1) - } - server.render('content.html', variables=vars) -def header(): #send headers to client +def home(): # render HTML page + vars = {"name": "MicroPython", "answer": (1 + 1)} + server.render("content.html", variables=vars) + + +def header(): # send headers to client server.sendStatus(server.OK) - server.sendHeaders({ - 'header1': 'one', - 'header2': 'two', - 'header3': 'three', - }) + server.sendHeaders( + {"header1": "one", "header2": "two", "header3": "three",} + ) + -def post(): #print JSON body from client +def post(): # print JSON body from client print(loadJSON(server.request_body).items()) + server.sendStatus(server.OK) + -def jsonn(): #send JSON to client - server.sendJSON({'status':'okkk'}) +def jsonn(): # send JSON to client + server.sendJSON({"status": "okkk"}) -#configure routes -server.routes(({ - (uWeb.GET, "/"): home, - (uWeb.POST, "/post"): post, - (uWeb.GET, "/json"): jsonn, - (uWeb.GET, "/header"): header -})) +# configure routes +server.routes( + ( + { + (uWeb.GET, "/"): home, + (uWeb.POST, "/post"): post, + (uWeb.GET, "/json"): jsonn, + (uWeb.GET, "/header"): header, + } + ) +) -#start server +# start server server.start() + ``` ### Example application using μWeb-uasyncio ```python import uasyncio + from uWeb_uasyncio import uWeb_uasyncio as uWeb from uWeb_uasyncio import loadJSON -server = uWeb("0.0.0.0", 8000) #init uWeb object +server = uWeb("0.0.0.0", 8000) # init uWeb object + -def home(): #render HTML page - vars = { - 'name': 'MicroPython', - 'answer': (1+1) - } - await server.render('content.html', variables=vars) +def home(): # render HTML page + vars = {"name": "MicroPython", "answer": (1 + 1)} + await server.render("content.html", variables=vars) -def printTen(): # counts to ten while still accepting incoming requests + +def printTen(): # counts to ten while still accepting incoming requests await server.sendStatus(server.OK) for i in range(10): print(i) await uasyncio.sleep(1) -def header(): #send headers to client + +def header(): # send headers to client await server.sendStatus(server.OK) - await server.sendHeaders({ - 'header1': 'one', - 'header2': 'two', - 'header3': 'three', - }) - -def post(): #print JSON body from client - print('Payload: ', loadJSON(server.request_body)) - await uasyncio.sleep(0) - -def jsonn(): #send JSON to client - await server.sendJSON({'status':'okkk'}) - -#configure routes -server.routes(({ - (uWeb.GET, "/"): home, - (uWeb.GET, "/ten"): printTen, - (uWeb.POST, "/post"): post, - (uWeb.GET, "/json"): jsonn, - (uWeb.GET, "/header"): header -})) - -#start server + await server.sendHeaders( + {"header1": "one", "header2": "two", "header3": "three",} + ) + + +def post(): # print JSON body from client + print("Payload: ", loadJSON(server.request_body)) + await server.sendStatus(server.OK) + + + +def jsonn(): # send JSON to client + await server.sendJSON({"status": "okkk"}) + + +# configure routes +server.routes( + ( + { + (uWeb.GET, "/"): home, + (uWeb.GET, "/ten"): printTen, + (uWeb.POST, "/post"): post, + (uWeb.GET, "/json"): jsonn, + (uWeb.GET, "/header"): header, + } + ) +) + +# start server server.start() ``` diff --git a/_config.yml b/_config.yml old mode 100644 new mode 100755 diff --git a/bin/micropython b/bin/micropython index a77fee5..653fd34 100755 Binary files a/bin/micropython and b/bin/micropython differ diff --git a/docs/uWeb-uasyncio.md b/docs/uWeb-uasyncio.md old mode 100644 new mode 100755 diff --git a/docs/uWeb.md b/docs/uWeb.md old mode 100644 new mode 100755 diff --git a/example/content.html b/example/content.html old mode 100644 new mode 100755 diff --git a/example/layout.html b/example/layout.html old mode 100644 new mode 100755 diff --git a/example/random.js b/example/random.js old mode 100644 new mode 100755 diff --git a/example/uWeb_example.py b/example/uWeb_example.py old mode 100644 new mode 100755 index a5f97c9..f7a0963 --- a/example/uWeb_example.py +++ b/example/uWeb_example.py @@ -1,37 +1,42 @@ import sys -sys.path.append('../uWeb') + +sys.path.append("../uWeb") # remove this when deploying to a board from uWeb import uWeb, loadJSON -server = uWeb("0.0.0.0", 8000) #init uWeb object +server = uWeb("0.0.0.0", 8000) # init uWeb object + + +def home(): # render HTML page + vars = {"name": "MicroPython", "answer": (1 + 1)} + server.render("content.html", variables=vars) -def home(): #render HTML page - vars = { - 'name': 'MicroPython', - 'answer': (1+1) - } - server.render('content.html', variables=vars) -def header(): #send headers to client +def header(): # send headers to client server.sendStatus(server.OK) - server.sendHeaders({ - 'header1': 'one', - 'header2': 'two', - 'header3': 'three', - }) + server.sendHeaders( + {"header1": "one", "header2": "two", "header3": "three",} + ) -def post(): #print JSON body from client + +def post(): # print JSON body from client print(loadJSON(server.request_body).items()) + server.sendStatus(server.OK) + -def jsonn(): #send JSON to client - server.sendJSON({'status':'okkk'}) +def jsonn(): # send JSON to client + server.sendJSON({"status": "okkk"}) -#configure routes -server.routes(({ - (uWeb.GET, "/"): home, - (uWeb.POST, "/post"): post, - (uWeb.GET, "/json"): jsonn, - (uWeb.GET, "/header"): header -})) +# configure routes +server.routes( + ( + { + (uWeb.GET, "/"): home, + (uWeb.POST, "/post"): post, + (uWeb.GET, "/json"): jsonn, + (uWeb.GET, "/header"): header, + } + ) +) -#start server +# start server server.start() diff --git a/example/uWeb_uasyncio_example.py b/example/uWeb_uasyncio_example.py old mode 100644 new mode 100755 index 69d8ede..939d7cc --- a/example/uWeb_uasyncio_example.py +++ b/example/uWeb_uasyncio_example.py @@ -1,47 +1,54 @@ import sys import uasyncio -sys.path.append('../uWeb') # remove this if deploying to a board + +sys.path.append("../uWeb") # remove this if deploying to a board from uWeb_uasyncio import uWeb_uasyncio as uWeb from uWeb_uasyncio import loadJSON -server = uWeb("0.0.0.0", 8000) #init uWeb object +server = uWeb("0.0.0.0", 8000) # init uWeb object + -def home(): #render HTML page - vars = { - 'name': 'MicroPython', - 'answer': (1+1) - } - await server.render('content.html', variables=vars) +def home(): # render HTML page + vars = {"name": "MicroPython", "answer": (1 + 1)} + await server.render("content.html", variables=vars) -def printTen(): # counts to ten while still accepting incoming requests + +def printTen(): # counts to ten while still accepting incoming requests await server.sendStatus(server.OK) for i in range(10): print(i) await uasyncio.sleep(1) -def header(): #send headers to client + +def header(): # send headers to client + await server.sendStatus(server.OK) + await server.sendHeaders( + {"header1": "one", "header2": "two", "header3": "three",} + ) + + +def post(): # print JSON body from client + print("Payload: ", loadJSON(server.request_body)) await server.sendStatus(server.OK) - await server.sendHeaders({ - 'header1': 'one', - 'header2': 'two', - 'header3': 'three', - }) - -def post(): #print JSON body from client - print('Payload: ', loadJSON(server.request_body)) - await uasyncio.sleep(0) - -def jsonn(): #send JSON to client - await server.sendJSON({'status':'okkk'}) - -#configure routes -server.routes(({ - (uWeb.GET, "/"): home, - (uWeb.GET, "/ten"): printTen, - (uWeb.POST, "/post"): post, - (uWeb.GET, "/json"): jsonn, - (uWeb.GET, "/header"): header -})) - -#start server + + + +def jsonn(): # send JSON to client + await server.sendJSON({"status": "okkk"}) + + +# configure routes +server.routes( + ( + { + (uWeb.GET, "/"): home, + (uWeb.GET, "/ten"): printTen, + (uWeb.POST, "/post"): post, + (uWeb.GET, "/json"): jsonn, + (uWeb.GET, "/header"): header, + } + ) +) + +# start server server.start() diff --git a/uWeb/404.html b/uWeb/404.html old mode 100644 new mode 100755 diff --git a/uWeb/500.html b/uWeb/500.html old mode 100644 new mode 100755 diff --git a/uWeb/layout.html b/uWeb/layout.html old mode 100644 new mode 100755 diff --git a/uWeb/uWeb.py b/uWeb/uWeb.py old mode 100644 new mode 100755 index 3f88057..269e112 --- a/uWeb/uWeb.py +++ b/uWeb/uWeb.py @@ -4,12 +4,13 @@ import network import sys + class uWeb: - version = 'uWeb-v1.1' - GET = 'GET' - POST = 'POST' - PUT = 'PUT' - DELETE = 'DELETE' + version = "uWeb-v1.1" + GET = "GET" + POST = "POST" + PUT = "PUT" + DELETE = "DELETE" OK = b"200 OK" NOT_FOUND = b"404 Not Found" @@ -19,18 +20,18 @@ class uWeb: ERROR = b"500 Internal Server Error" MIME_TYPES = { - 'css': 'text/css', - 'html': 'text/html', - 'jpeg': 'image/jpeg', - 'jpg': 'image/jpeg', - 'js': 'text/javascript', - 'json': 'application/json', - 'rtf': 'application/rtf', - 'svg': 'image/svg+xml' + "css": "text/css", + "html": "text/html", + "jpeg": "image/jpeg", + "jpg": "image/jpeg", + "js": "text/javascript", + "json": "application/json", + "rtf": "application/rtf", + "svg": "image/svg+xml", } def __init__(self, address, port): - #configure socket + # configure socket self.address = address self.port = port self.active_socket = socket.socket() @@ -39,30 +40,30 @@ def __init__(self, address, port): self.address = self.address_info[0][-1] print("Bind address info:", self.address_info[0][4]) self.setSupportedFileTypes() - self.routes() #init empty routes_dict + self.routes() # init empty routes_dict self.active_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.active_socket.bind(self.address) self.active_socket.listen(5) - #BACKEND SERVER METHODS + # BACKEND SERVER METHODS def routes(self, routes={}): # set routes dict self.routes_dict = routes def router(self): if len(self.routes_dict) == 0: - self.render('welcome.html') + self.render("welcome.html") elif self.request_command: if (self.request_command, self.request_path) in self.routes_dict.keys(): # check for valid route self.routes_dict[(self.request_command, self.request_path)]() - elif ('.' in self.request_path): - #send file to client + elif "." in self.request_path: + # send file to client self.sendFile(self.request_path[1:]) else: - self.render('404.html', layout=None, status=self.NOT_FOUND) + self.render("404.html", layout=None, status=self.NOT_FOUND) else: - self.render('505.html', layout=None, status=self.ERROR) + self.render("505.html", layout=None, status=self.ERROR) def start(self, log=True): self.log = log @@ -80,7 +81,7 @@ def start(self, log=True): print("Client socket:", self.client_socket) print("Client Request:") self.request_line = self.client_socket.readline() - if bool(self.request_line): #check if request not empty + if bool(self.request_line): # check if request not empty if self.log: print(self.request_line.decode().strip()) self.resolveRequestLine() @@ -90,83 +91,87 @@ def start(self, log=True): except Exception as e: sys.print_exception(e) - def render(self, html_file, layout='layout.html', variables=False, status=OK): + def render(self, html_file, layout="layout.html", variables=False, status=OK): # send HTML file to client try: if layout: # layout rendering file = layout - with open(layout, 'r') as f: + with open(layout, "r") as f: gc.collect() self.sendStatus(status) - self.sendHeaders({'Content-Type': 'text/html'}) - self.send(b'\n') + self.sendHeaders({"Content-Type": "text/html"}) + self.send(b"\n") for line in f: - if '{{yield}}' in line: - splitted = line.split('{{yield}}') + if "{{yield}}" in line: + splitted = line.split("{{yield}}") self.send(splitted[0].encode()) - with open(html_file, 'r') as f: + with open(html_file, "r") as f: for line in f: if variables: for var_name, value in variables.items(): - line = line.replace("{{%s}}" % var_name, str(value)) + line = line.replace( + "{{%s}}" % var_name, str(value) + ) self.send(line.encode()) self.send(splitted[1].encode()) - else: + else: self.send(line.encode()) else: # no layout rendering gc.collect() self.sendStatus(status) - self.sendHeaders({'Content-Type': 'text/html'}) - self.send(b'\n') + self.sendHeaders({"Content-Type": "text/html"}) + self.send(b"\n") file = html_file - with open(html_file, 'r') as f: + with open(html_file, "r") as f: for line in f: if variables: for var_name, value in variables.items(): line = line.replace("{{%s}}" % var_name, str(value)) self.send(line.encode()) - self.send(b'\n\n') + self.send(b"\n\n") except Exception as e: if e.args[0] == 2: - #catch file not found - print('No such file: %s' % file) - self.render('500.html', layout=None, status=self.ERROR) + # catch file not found + print("No such file: %s" % file) + self.render("500.html", layout=None, status=self.ERROR) else: sys.print_exception(e) def sendJSON(self, dict_to_send={}): # send JSON data to client self.sendStatus(self.OK) - self.sendHeaders({'Content-Type': 'application/json'}) + self.sendHeaders({"Content-Type": "application/json"}) self.sendBody(json.dumps(dict_to_send)) def sendFile(self, filename): # send file(ie: js, css) to client - name, extension = filename.split('.') + name, extension = filename.split(".") try: if extension in self.supported_file_types: # check if included in allowed file types - with open(filename, 'r') as f: + with open(filename, "r") as f: self.sendStatus(self.OK) if extension in self.MIME_TYPES.keys(): - self.sendHeaders({'Content-Type': self.MIME_TYPES[extension]}) # send content type - self.send(b'\n') + self.sendHeaders( + {"Content-Type": self.MIME_TYPES[extension]} + ) # send content type + self.send(b"\n") for line in f: self.send(line.encode()) - self.send(b'\n\n') + self.send(b"\n\n") else: self.sendStatus(self.ERROR) - print('File: %s is not an allowed file' % filename) + print("File: %s is not an allowed file" % filename) except Exception as e: self.sendStatus(self.NOT_FOUND) - print('File: %s was not found, so 404 was sent to client.' % filename) + print("File: %s was not found, so 404 was sent to client." % filename) def sendStatus(self, status_code): # send HTTP header w/ status to client response_line = b"HTTP/1.1 " - self.send(response_line + status_code + b'\n') + self.send(response_line + status_code + b"\n") def sendHeaders(self, headers_dict={}): # send HTTP headers to client @@ -176,18 +181,18 @@ def sendHeaders(self, headers_dict={}): def sendBody(self, body_content): # send HTTP body content to client - self.send(b'\n' + body_content + b'\n\n') + self.send(b"\n" + body_content + b"\n\n") - def setSupportedFileTypes(self, file_types = ['js', 'css']): - #set allowed file types to be sent if requested + def setSupportedFileTypes(self, file_types=["js", "css"]): + # set allowed file types to be sent if requested self.supported_file_types = file_types - #HELPER METHODS + # HELPER METHODS def readFile(self, file): # read file and encode try: - with open(file, 'r') as f: - return ''.join(f.readlines()).encode() + with open(file, "r") as f: + return "".join(f.readlines()).encode() except Exception as e: print(e) @@ -196,11 +201,11 @@ def send(self, content): self.client_socket.write(content) def processRequest(self): - #process request from client --> extract headers + body + # process request from client --> extract headers + body raw_headers = [] self.request_headers = {} - #extract headers + # extract headers while True: h = self.client_socket.readline() if h == b"" or h == b"\r\n": @@ -209,19 +214,20 @@ def processRequest(self): print(h.decode().strip()) raw_headers.append(h) for header in raw_headers: - split_header = header.decode().strip().split(': ') + split_header = header.decode().strip().split(": ") self.request_headers[split_header[0]] = split_header[1] # extract body if its a POST request if self.request_command == self.POST: - self.request_body = self.client_socket.read(int(self.request_headers['Content-Length'])).decode() + self.request_body = self.client_socket.read( + int(self.request_headers["Content-Length"]) + ).decode() if self.log: print(self.request_body) - self.sendStatus(self.OK) def resolveRequestLine(self): # parse request line from client - req_line = self.request_line.decode().strip().split(' ') + req_line = self.request_line.decode().strip().split(" ") if len(req_line) > 1: self.request_command = req_line[0] self.request_path = req_line[1] @@ -230,6 +236,7 @@ def resolveRequestLine(self): else: return False + def loadJSON(string): # turn JSON string to dict return json.loads(string) diff --git a/uWeb/uWeb_uasyncio.py b/uWeb/uWeb_uasyncio.py old mode 100644 new mode 100755 index b282a1c..0b32c32 --- a/uWeb/uWeb_uasyncio.py +++ b/uWeb/uWeb_uasyncio.py @@ -4,12 +4,13 @@ import sys import uasyncio + class uWeb_uasyncio: - version = 'uWeb-uasyncio-v1.0' - GET = 'GET' - POST = 'POST' - PUT = 'PUT' - DELETE = 'DELETE' + version = "uWeb-uasyncio-v1.0" + GET = "GET" + POST = "POST" + PUT = "PUT" + DELETE = "DELETE" OK = b"200 OK" NOT_FOUND = b"404 Not Found" @@ -19,14 +20,14 @@ class uWeb_uasyncio: ERROR = b"500 Internal Server Error" MIME_TYPES = { - 'css': 'text/css', - 'html': 'text/html', - 'jpeg': 'image/jpeg', - 'jpg': 'image/jpeg', - 'js': 'text/javascript', - 'json': 'application/json', - 'rtf': 'application/rtf', - 'svg': 'image/svg+xml' + "css": "text/css", + "html": "text/html", + "jpeg": "image/jpeg", + "jpg": "image/jpeg", + "js": "text/javascript", + "json": "application/json", + "rtf": "application/rtf", + "svg": "image/svg+xml", } def __init__(self, address, port): @@ -34,19 +35,23 @@ def __init__(self, address, port): self.port = port self.setSupportedFileTypes() - self.routes() #init empty routes_dict - + self.routes() # init empty routes_dict - #BACKEND SERVER METHODS + # BACKEND SERVER METHODS def routes(self, routes={}): # set routes dict - self.routes_dict = routes + self.routes_dict = routes def start(self, log=True): self.log = log loop = uasyncio.get_event_loop() - loop.create_task(uasyncio.start_server(self.router, self.address, self.port)) # Schedule server loop - # TODO: uncomment on release print("uWeb server started! Connect to http://%s:%s/" % (network.WLAN(network.STA_IF).ifconfig()[0], self.port)) + loop.create_task( + uasyncio.start_server(self.router, self.address, self.port) + ) # Schedule server loop + print( + "uWeb server started! Connect to http://%s:%s/" + % (network.WLAN(network.STA_IF).ifconfig()[0], self.port) + ) loop.run_forever() def router(self, reader, writer): @@ -57,77 +62,88 @@ def router(self, reader, writer): if not self.log: print("Server logs are currently off.") if self.log: - print('INCOMING REQUEST FROM %s' % (writer.get_extra_info('peername'))) - print('----------------') - if bool(self.request): #check if request not empty + print("INCOMING REQUEST FROM %s" % (writer.get_extra_info("peername"))) + print("----------------") + if bool(self.request): # check if request not empty if self.log: print(self.request.decode().strip()) print() self.processRequest() if len(self.routes_dict) == 0: - await self.render('welcome.html') + await self.render("welcome.html") elif self.request_command: - if (self.request_command, self.request_path) in self.routes_dict.keys(): + if ( + self.request_command, + self.request_path, + ) in self.routes_dict.keys(): # check for valid route loop = uasyncio.get_event_loop() - loop.create_task(self.routes_dict[(self.request_command, self.request_path)]()) - elif ('.' in self.request_path): - #send file to client + loop.create_task( + self.routes_dict[ + (self.request_command, self.request_path) + ]() + ) + elif "." in self.request_path: + # send file to client await self.sendFile(self.request_path[1:]) else: - await self.render('404.html', layout=None, status=self.NOT_FOUND) + await self.render( + "404.html", layout=None, status=self.NOT_FOUND + ) else: - await self.render('505.html', layout=None, status=self.ERROR) + await self.render("505.html", layout=None, status=self.ERROR) await writer.aclose() - if self.log: - print('closed connection') + if self.log: + print("closed connection") print() except Exception as e: sys.print_exception(e) - def render(self, html_file, layout='layout.html', variables=False, status=OK): + def render(self, html_file, layout="layout.html", variables=False, status=OK): # send HTML file to client try: if layout: # layout rendering file = layout - with open(layout, 'r') as f: + with open(layout, "r") as f: gc.collect() await self.sendStatus(status) - await self.sendHeaders({'Content-Type': 'text/html'}) - await self.send(b'\n') + await self.sendHeaders({"Content-Type": "text/html"}) + await self.send(b"\n") for line in f: - if '{{yield}}' in line: - splitted = line.split('{{yield}}') + if "{{yield}}" in line: + splitted = line.split("{{yield}}") await self.send(splitted[0].encode()) - with open(html_file, 'r') as f: + with open(html_file, "r") as f: for line in f: if variables: for var_name, value in variables.items(): - line = line.replace("{{%s}}" % var_name, str(value)) + line = line.replace( + "{{%s}}" % var_name, str(value) + ) await self.send(line.encode()) await self.send(splitted[1].encode()) - else: + else: await self.send(line.encode()) else: # no layout rendering gc.collect() await self.sendStatus(status) - await self.sendHeaders({'Content-Type': 'text/html'}) - await self.send(b'\n') + await self.sendHeaders({"Content-Type": "text/html"}) + await self.send(b"\n") file = html_file - with open(html_file, 'r') as f: + with open(html_file, "r") as f: for line in f: if variables: for var_name, value in variables.items(): line = line.replace("{{%s}}" % var_name, str(value)) await self.send(line.encode()) - await self.send(b'\n\n') + await self.send(b"\n\n") except Exception as e: if e.args[0] == 2: - #catch file not found - print('No such file: %s' % file) - await self.render('500.html', layout=None, status=self.ERROR) + # catch file not found + print("No such file: %s" % file) + await self.render("500.html", layout=None, status=self.ERROR) else: sys.print_exception(e) # uasyncio.sleep(0) @@ -135,34 +151,36 @@ def render(self, html_file, layout='layout.html', variables=False, status=OK): def sendJSON(self, dict_to_send={}): # send JSON data to client await self.sendStatus(self.OK) - await self.sendHeaders({'Content-Type': 'application/json'}) + await self.sendHeaders({"Content-Type": "application/json"}) await self.sendBody(json.dumps(dict_to_send)) def sendFile(self, filename): # send file(ie: js, css) to client - name, extension = filename.split('.') + name, extension = filename.split(".") try: if extension in self.supported_file_types: # check if included in allowed file types - with open(filename, 'r') as f: + with open(filename, "r") as f: await self.sendStatus(self.OK) if extension in self.MIME_TYPES.keys(): - await self.sendHeaders({'Content-Type': self.MIME_TYPES[extension]}) # send content type - await self.send(b'\n') + await self.sendHeaders( + {"Content-Type": self.MIME_TYPES[extension]} + ) # send content type + await self.send(b"\n") for line in f: await self.send(line.encode()) - await self.send(b'\n\n') + await self.send(b"\n\n") else: await self.sendStatus(self.ERROR) - print('File: %s is not an allowed file' % filename) + print("File: %s is not an allowed file" % filename) except Exception as e: await self.sendStatus(self.NOT_FOUND) - print('File: %s was not found, so 404 was sent to client.' % filename) + print("File: %s was not found, so 404 was sent to client." % filename) def sendStatus(self, status_code): # send HTTP header w/ status to client response_line = b"HTTP/1.1 " - await self.send(response_line + status_code + b'\n') + await self.send(response_line + status_code + b"\n") def sendHeaders(self, headers_dict={}): # send HTTP headers to client @@ -171,35 +189,35 @@ def sendHeaders(self, headers_dict={}): def sendBody(self, body_content): # send HTTP body content to client - await self.send(b'\n' + body_content + b'\n\n') + await self.send(b"\n" + body_content + b"\n\n") - def setSupportedFileTypes(self, file_types = ['js', 'css']): - #set allowed file types to be sent if requested + def setSupportedFileTypes(self, file_types=["js", "css"]): + # set allowed file types to be sent if requested self.supported_file_types = file_types - #HELPER METHODS + # HELPER METHODS def readFile(self, file): # read file and encode try: - with open(file, 'r') as f: - return ''.join(f.readlines()).encode() + with open(file, "r") as f: + return "".join(f.readlines()).encode() except Exception as e: print(e) def send(self, content): # send to client @ socket-level if self.log: - print('sending: ', content) + print("sending: ", content) await self.writer.awrite(content) def processRequest(self): # process request from client --> extract request line + headers + body # parse request line and headers from client - request_line, rest_of_request = self.request.split(b'\r\n', 1) + request_line, rest_of_request = self.request.split(b"\r\n", 1) - #extract request line - request_line = request_line.decode().strip().split(' ') + # extract request line + request_line = request_line.decode().strip().split(" ") if len(request_line) > 1: self.request_command = request_line[0] self.request_path = request_line[1] @@ -207,16 +225,16 @@ def processRequest(self): # extract headers self.request_headers = {} - raw_headers, body = rest_of_request.split(b'\r\n\r\n', 1) - raw_headers = raw_headers.split(b'\r\n') + raw_headers, body = rest_of_request.split(b"\r\n\r\n", 1) + raw_headers = raw_headers.split(b"\r\n") for header in raw_headers: - split_header = header.decode().strip().split(': ') + split_header = header.decode().strip().split(": ") self.request_headers[split_header[0]] = split_header[1] - # extract body if its a POST request and send OK status + # extract body if its a POST request if self.request_command == self.POST: self.request_body = body.decode() - self.sendStatus(self.OK) + def loadJSON(string): # turn JSON string to dict diff --git a/uWeb/welcome.html b/uWeb/welcome.html old mode 100644 new mode 100755