|
| 1 | +import gc |
| 2 | +import re |
| 3 | +import os |
| 4 | + |
| 5 | + |
| 6 | +url_pat = re.compile( |
| 7 | + r'^(([^:/\\?#]+):)?' + # scheme # NOQA |
| 8 | + r'(//([^/\\?#]*))?' + # user:pass@host:port # NOQA |
| 9 | + r'([^\\?#]*)' + # route # NOQA |
| 10 | + r'(\\?([^#]*))?' + # query # NOQA |
| 11 | + r'(#(.*))?') # fragment # NOQA |
| 12 | + |
| 13 | + |
| 14 | +def pre_route(file): |
| 15 | + |
| 16 | + async def _func(writer): |
| 17 | + await send_file(writer, file) |
| 18 | + |
| 19 | + return _func |
| 20 | + |
| 21 | + |
| 22 | +routes = {} |
| 23 | + |
| 24 | +# b'/': pre_route('/www/page.htm'), |
| 25 | +# b'/static/jquery.js': pre_route('/www/jquery-3.5.1.min.js')} |
| 26 | + |
| 27 | + |
| 28 | +def route(location, resource): |
| 29 | + global routes |
| 30 | + routes[location] = pre_route(resource) |
| 31 | + |
| 32 | + |
| 33 | +async def send_file(writer, file): |
| 34 | + fstat = os.stat(file) |
| 35 | + fsize = fstat[6] |
| 36 | + |
| 37 | + writer.write(b'HTTP/1.1 200 OK\r\n') |
| 38 | + writer.write(b'Content-Type: text/html\r\n') |
| 39 | + writer.write('Content-Length: {}\r\n'.format(fsize).encode('utf-8')) |
| 40 | + writer.write(b'Accept-Ranges: none\r\n') |
| 41 | + writer.write(b'Transfer-Encoding: chunked\r\n') |
| 42 | + writer.write(b'\r\n') |
| 43 | + await writer.drain() |
| 44 | + gc.collect() |
| 45 | + max_chunk_size = 1024 |
| 46 | + with open(file, 'rb') as f: |
| 47 | + for x in range(0, fsize, max_chunk_size): |
| 48 | + chunk_size = min(max_chunk_size, fsize-x) |
| 49 | + chunk_header = "{:x}\r\n".format(chunk_size).encode('utf-8') |
| 50 | + writer.write(chunk_header) |
| 51 | + writer.write(f.read(chunk_size)) |
| 52 | + writer.write(b'\r\n') |
| 53 | + await writer.drain() |
| 54 | + gc.collect() |
| 55 | + writer.write(b"0\r\n") |
| 56 | + writer.write(b"\r\n") |
| 57 | + await writer.drain() |
| 58 | + writer.close() |
| 59 | + await writer.wait_closed() |
| 60 | + gc.collect() |
| 61 | + |
| 62 | + |
| 63 | +async def server(reader, writer): |
| 64 | + req = await reader.readline() |
| 65 | + print(req) |
| 66 | + method, uri, proto = req.split(b" ") |
| 67 | + m = re.match(url_pat, uri) |
| 68 | + route_req = m.group(5) |
| 69 | + |
| 70 | + while True: |
| 71 | + h = await reader.readline() |
| 72 | + if h == b"" or h == b"\r\n": |
| 73 | + break |
| 74 | + print(h) |
| 75 | + |
| 76 | + print("route: {}".format(route_req.decode('utf-8'))) |
| 77 | + test = route_req in routes |
| 78 | + print("Route found?: {}".format(test)) |
| 79 | + |
| 80 | + if route_req in routes: |
| 81 | + await routes[route_req](writer) |
| 82 | + else: |
| 83 | + writer.write(b'HTTP/1.0 404 Not Found\r\n') |
| 84 | + writer.write(b'\r\n') |
| 85 | + await writer.drain() |
| 86 | + writer.close() |
| 87 | + await writer.wait_closed() |
| 88 | + gc.collect() |
0 commit comments