|
| 1 | +# file: simple_server.py |
| 2 | + |
| 3 | +"""Simple HTTP server with GET that waits for given seconds. |
| 4 | +""" |
| 5 | + |
| 6 | +from http.server import BaseHTTPRequestHandler, HTTPServer |
| 7 | +from socketserver import ThreadingMixIn |
| 8 | +import time |
| 9 | + |
| 10 | + |
| 11 | +ENCODING = 'utf-8' |
| 12 | + |
| 13 | + |
| 14 | +class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): |
| 15 | + """Simple multi-threaded HTTP server. |
| 16 | + """ |
| 17 | + pass |
| 18 | + |
| 19 | + |
| 20 | +class MyRequestHandler(BaseHTTPRequestHandler): |
| 21 | + """Very simple request handler. Only supports GET. |
| 22 | + """ |
| 23 | + |
| 24 | + def do_GET(self): # pylint: disable=invalid-name |
| 25 | + """Respond after seconds given in path. |
| 26 | + """ |
| 27 | + try: |
| 28 | + seconds = float(self.path[1:]) |
| 29 | + except ValueError: |
| 30 | + seconds = 0.0 |
| 31 | + text = "Waited for {:4.2f} seconds.\nThat's all.\n" |
| 32 | + msg = text.format(seconds).encode(ENCODING) |
| 33 | + time.sleep(seconds) |
| 34 | + self.send_response(200) |
| 35 | + self.send_header("Content-type", 'text/plain; charset=utf-8') |
| 36 | + self.send_header("Content-length", str(len(msg))) |
| 37 | + self.end_headers() |
| 38 | + self.wfile.write(msg) |
| 39 | + |
| 40 | + |
| 41 | +def run(server_class=ThreadingHTTPServer, |
| 42 | + handler_class=MyRequestHandler, |
| 43 | + port=8000): |
| 44 | + """Run the simple server on given port. |
| 45 | + """ |
| 46 | + server_address = ('', port) |
| 47 | + httpd = server_class(server_address, handler_class) |
| 48 | + print('Serving from port {} ...'.format(port)) |
| 49 | + httpd.serve_forever() |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == '__main__': |
| 53 | + run() |
0 commit comments