|
| 1 | +# https://docs.python.org/3/howto/sockets.html |
| 2 | +# https://stackoverflow.com/questions/8627986/how-to-keep-a-socket-open-until-client-closes-it |
| 3 | +# https://stackoverflow.com/questions/10091271/how-can-i-implement-a-simple-web-server-using-python-without-using-any-libraries |
| 4 | + |
| 5 | +from socket import * |
| 6 | +import traceback, json |
| 7 | +from dataclasses import dataclass |
| 8 | +from dataclasses import field |
| 9 | +import sys |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class HttpRequest: |
| 13 | + method: str = "" |
| 14 | + path: str = "" |
| 15 | + headers: dict = field(default_factory=dict) |
| 16 | + body: str = "" |
| 17 | + |
| 18 | +@dataclass |
| 19 | +class HttpResponse: |
| 20 | + code: str = "200" |
| 21 | + headers: dict = field(default_factory=dict) |
| 22 | + _body: list = field(default_factory=list) |
| 23 | + |
| 24 | + def println(self, line: str) : |
| 25 | + self._body.append(line) |
| 26 | + |
| 27 | +def parseRequest(rd:str) -> HttpRequest: |
| 28 | + retval = HttpRequest() |
| 29 | + retval.body = rd |
| 30 | + ipos = rd.find("\r\n\r\n") |
| 31 | + if ipos < 1 : |
| 32 | + print('Incorrectly formatted request input') |
| 33 | + print(repr(rd)) |
| 34 | + return None |
| 35 | + |
| 36 | + # Find the blank line between HEAD and BODY |
| 37 | + head = rd[0:ipos-1] |
| 38 | + lines = head.split("\n") |
| 39 | + |
| 40 | + # GET / HTTP/1.1 |
| 41 | + if len(lines) > 0 : |
| 42 | + firstline = lines[0] |
| 43 | + pieces = firstline.split(' ') |
| 44 | + if len(pieces) >= 2 : |
| 45 | + retval.method = pieces[0] or 'Missing'; |
| 46 | + retval.path = pieces[1] or 'Missing'; |
| 47 | + |
| 48 | + # Accept-Language: en-US,en;q=0.5 |
| 49 | + for line in lines: |
| 50 | + line = line.strip() |
| 51 | + pieces = line.split(": ", 1) |
| 52 | + if len(pieces) != 2 : continue |
| 53 | + retval.headers[pieces[0].strip()] = pieces[1].strip() |
| 54 | + return retval |
| 55 | + |
| 56 | +def responseSend(clientsocket, response: HttpResponse) : |
| 57 | + |
| 58 | + try: |
| 59 | + print('==== Sending Response Headers') |
| 60 | + firstline = "HTTP/1.1 "+response.code+" OK\r\n" |
| 61 | + clientsocket.sendall(firstline.encode()) |
| 62 | + for key, value in response.headers.items(): |
| 63 | + print(key+': '+value) |
| 64 | + clientsocket.sendall(key.encode()) |
| 65 | + clientsocket.sendall(": ".encode()) |
| 66 | + clientsocket.sendall(value.encode()) |
| 67 | + clientsocket.sendall("\r\n".encode()) |
| 68 | + |
| 69 | + |
| 70 | + clientsocket.sendall("\r\n".encode()) |
| 71 | + chars = 0 |
| 72 | + for line in response._body: |
| 73 | + line = patchAutograder(line) |
| 74 | + |
| 75 | + chars += len(line) |
| 76 | + clientsocket.sendall(line.replace("\n", "\r\n").encode()) |
| 77 | + clientsocket.sendall("\r\n".encode()) |
| 78 | + print("==== Sent",chars,"characters body output") |
| 79 | + |
| 80 | + except Exception as exc : |
| 81 | + print(exc) |
| 82 | + print(response) |
| 83 | + print(traceback.format_exc()) |
| 84 | + |
| 85 | +# If we are sending HTML, include the endpoint for the DJ4E JavaScript autograder |
| 86 | +# For local dev testing, this can be run as |
| 87 | +# python runserver.py 9000 http://localhost:8888/dj4e/tools/jsauto/autograder.js |
| 88 | + |
| 89 | +def patchAutograder(line: str) -> str: |
| 90 | + if line.find('</body>') == -1 : return line |
| 91 | + dj4e_autograder = "https://www.dj4e.com/tools/jsauto/autograder.js" |
| 92 | + if len(sys.argv) > 2 : |
| 93 | + dj4e_autograder = sys.argv[2] |
| 94 | + return line.replace('</body>', '\n<script src="'+dj4e_autograder+'"></script>\n</body>'); |
| 95 | + |
| 96 | +def httpServer(router): |
| 97 | + port = 9000 |
| 98 | + if len(sys.argv) > 1 : |
| 99 | + port = int(sys.argv[1]) |
| 100 | + |
| 101 | + print('\n================ Starting mini_django server on '+str(port)) |
| 102 | + serversocket = socket(AF_INET, SOCK_STREAM) |
| 103 | + try : |
| 104 | + serversocket.bind(('localhost',port)) |
| 105 | + serversocket.listen(5) |
| 106 | + while(1): |
| 107 | + print('\n================ Waiting for the Next Request') |
| 108 | + (clientsocket, address) = serversocket.accept() |
| 109 | + |
| 110 | + rd = clientsocket.recv(5000).decode() |
| 111 | + print('====== Received Headers') |
| 112 | + print(rd) |
| 113 | + request = parseRequest(rd) |
| 114 | + |
| 115 | + # If we did not get a valid request, send a 500 |
| 116 | + if not isinstance(request, HttpRequest) : |
| 117 | + response = view_fail(request, "500", "Request could not be parsed") |
| 118 | + |
| 119 | + # Send valid request to the router (urls.py) |
| 120 | + else: |
| 121 | + response = router(request) |
| 122 | + |
| 123 | + # If we did not get a valid response, log it and send back a 500 |
| 124 | + if not isinstance(response, HttpResponse) : |
| 125 | + response = view_fail(request, "500", "Response returned from router / view is not of type HttpResponse") |
| 126 | + |
| 127 | + try: |
| 128 | + responseSend(clientsocket, response) |
| 129 | + clientsocket.shutdown(SHUT_WR) |
| 130 | + except Exception as exc : |
| 131 | + print(exc) |
| 132 | + print(traceback.format_exc()) |
| 133 | + |
| 134 | + except KeyboardInterrupt : |
| 135 | + print("\nShutting down...\n") |
| 136 | + except Exception as exc : |
| 137 | + print(exc) |
| 138 | + print(traceback.format_exc()) |
| 139 | + |
| 140 | + print("Closing socket") |
| 141 | + serversocket.close() |
| 142 | + |
| 143 | +def view_fail(req: HttpRequest, code: str, failure: str) -> HttpResponse: |
| 144 | + res = HttpResponse() |
| 145 | + |
| 146 | + print(" ") |
| 147 | + print("Sending view_fail, code="+code+" failure="+failure) |
| 148 | + |
| 149 | + res.code = code |
| 150 | + |
| 151 | + res.headers['Content-Type'] = 'text/html; charset=utf-8' |
| 152 | + |
| 153 | + res.println('<html><body>') |
| 154 | + if res.code == "404" : |
| 155 | + res.println('<div style="background-color: rgb(255, 255, 204);">') |
| 156 | + else : |
| 157 | + res.println('<div style="background-color: pink;">') |
| 158 | + |
| 159 | + res.println('<b>Page has errors</b>') |
| 160 | + res.println('<div><b>Request Method:</b> '+req.method+"</div>") |
| 161 | + res.println('<div><b>Request URL:</b> '+req.path+'</div>') |
| 162 | + res.println('<div><b>Response Failure:</b> '+failure+'</div>') |
| 163 | + res.println('<div><b>Response Code:</b> '+res.code+'</div>') |
| 164 | + res.println("</div><pre>") |
| 165 | + res.println("Valid paths: /dj4e /js4e or /404") |
| 166 | + res.println("\nRequest header data:") |
| 167 | + res.println(json.dumps(req.headers, indent=4)) |
| 168 | + res.println("</pre></body></html>") |
| 169 | + return res |
| 170 | + |
| 171 | + |
0 commit comments