|
| 1 | +""" |
| 2 | +MicroPyServer is a simple HTTP server for MicroPython projects. |
| 3 | +
|
| 4 | +@see https://github.com/troublegum/micropyserver |
| 5 | +
|
| 6 | +The MIT License |
| 7 | +
|
| 8 | +Copyright (c) 2019 troublegum. https://github.com/troublegum/micropyserver |
| 9 | +
|
| 10 | +Permission is hereby granted, free of charge, to any person obtaining a copy |
| 11 | +of this software and associated documentation files (the "Software"), to deal |
| 12 | +in the Software without restriction, including without limitation the rights |
| 13 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 14 | +copies of the Software, and to permit persons to whom the Software is |
| 15 | +furnished to do so, subject to the following conditions: |
| 16 | +
|
| 17 | +The above copyright notice and this permission notice shall be included in |
| 18 | +all copies or substantial portions of the Software. |
| 19 | +
|
| 20 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 21 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 22 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 23 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 24 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 25 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 26 | +THE SOFTWARE. |
| 27 | +""" |
| 28 | +import re |
| 29 | +import socket |
| 30 | +import sys |
| 31 | + |
| 32 | + |
| 33 | +class MicroPyServer(object): |
| 34 | + |
| 35 | + def __init__(self, host="0.0.0.0", port=80): |
| 36 | + """ Constructor """ |
| 37 | + self._host = host |
| 38 | + self._port = port |
| 39 | + self._routes = [] |
| 40 | + self._connect = None |
| 41 | + self._on_request_handler = None |
| 42 | + |
| 43 | + def start(self): |
| 44 | + """ Start server """ |
| 45 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 46 | + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 47 | + sock.bind((self._host, self._port)) |
| 48 | + sock.listen(1) |
| 49 | + while True: |
| 50 | + try: |
| 51 | + self._connect, address = sock.accept() |
| 52 | + request = self._get_request() |
| 53 | + if len(request) == 0: |
| 54 | + self._connect.close() |
| 55 | + continue |
| 56 | + if self._on_request_handler: |
| 57 | + if not self._on_request_handler(request, address): |
| 58 | + continue |
| 59 | + route = self.find_route(request) |
| 60 | + if route: |
| 61 | + route["handler"](request) |
| 62 | + else: |
| 63 | + self.not_found() |
| 64 | + except Exception as e: |
| 65 | + try: |
| 66 | + self.internal_error(str(e)) |
| 67 | + except Exception as e: |
| 68 | + sys.print_exception(e) |
| 69 | + finally: |
| 70 | + self._connect.close() |
| 71 | + |
| 72 | + def add_route(self, path, handler, method="GET"): |
| 73 | + """ Add new route """ |
| 74 | + self._routes.append({"path": path, "handler": handler, "method": method}) |
| 75 | + |
| 76 | + def send(self, response, status=200, content_type="Content-Type: text/plain", extra_headers=[]): |
| 77 | + """ Send response to client """ |
| 78 | + if self._connect is None: |
| 79 | + raise Exception("Can't send response, no connection instance") |
| 80 | + |
| 81 | + status_message = {200: "OK", 400: "Bad Request", 403: "Forbidden", 404: "Not Found", |
| 82 | + 500: "Internal Server Error"} |
| 83 | + self._connect.sendall("HTTP/1.0 " + str(status) + " " + status_message[status] + "\r\n") |
| 84 | + self._connect.sendall(content_type + "\r\n") |
| 85 | + for header in extra_headers: |
| 86 | + self._connect.sendall(header + "\r\n") |
| 87 | + self._connect.sendall("X-Powered-By: MicroPyServer\r\n") |
| 88 | + self._connect.sendall("\r\n") |
| 89 | + self._connect.sendall(response) |
| 90 | + |
| 91 | + def find_route(self, request): |
| 92 | + """ Find route """ |
| 93 | + lines = request.split("\r\n") |
| 94 | + method = re.search("^([A-Z]+)", lines[0]).group(1) |
| 95 | + path = re.search("^[A-Z]+\\s+(/[-a-zA-Z0-9_.]*)", lines[0]).group(1) |
| 96 | + for route in self._routes: |
| 97 | + if method != route["method"]: |
| 98 | + continue |
| 99 | + if path == route["path"]: |
| 100 | + return route |
| 101 | + else: |
| 102 | + match = re.search("^" + route["path"] + "$", path) |
| 103 | + if match: |
| 104 | + print(method, path, route["path"]) |
| 105 | + return route |
| 106 | + |
| 107 | + def not_found(self): |
| 108 | + """ Not found action """ |
| 109 | + self.send("404", status=404) |
| 110 | + |
| 111 | + def internal_error(self, error): |
| 112 | + """ Catch error action """ |
| 113 | + self.send("Error: " + error, status=500) |
| 114 | + sys.exc_info() |
| 115 | + |
| 116 | + def on_request(self, handler): |
| 117 | + """ Set request handler """ |
| 118 | + self._on_request_handler = handler |
| 119 | + |
| 120 | + def _get_request(self): |
| 121 | + """ Return request body """ |
| 122 | + return str(self._connect.recv(4096), "utf8") |
0 commit comments