adam | 6142bef | 2018-10-01 10:34:19 +0200 | [diff] [blame^] | 1 | import logging |
| 2 | from http.server import BaseHTTPRequestHandler, HTTPServer |
| 3 | |
| 4 | DEFAULT_PORT = 8443 |
| 5 | |
| 6 | |
| 7 | class SOHandler(BaseHTTPRequestHandler): |
| 8 | |
| 9 | def __init__(self, request, client_address, server): |
| 10 | self.response_on_get = self._read_on_get_response() |
| 11 | super().__init__(request, client_address, server) |
| 12 | |
| 13 | def do_POST(self): |
| 14 | logging.info('POST called') |
| 15 | self.send_response(200) |
| 16 | self._set_headers() |
| 17 | |
| 18 | self.wfile.write(self.response_on_get.encode("utf-8")) |
| 19 | return |
| 20 | |
| 21 | def do_GET(self): |
| 22 | logging.info('GET called') |
| 23 | self.send_response(200) |
| 24 | self._set_headers() |
| 25 | |
| 26 | self.wfile.write(self.response_on_get.encode("utf-8")) |
| 27 | return |
| 28 | |
| 29 | def _set_headers(self): |
| 30 | self.send_header('Content-Type', 'application/json') |
| 31 | self.end_headers() |
| 32 | |
| 33 | @staticmethod |
| 34 | def _read_on_get_response(): |
| 35 | with open('so_post_response.json', 'r') as file: |
| 36 | return file.read() |
| 37 | |
| 38 | |
| 39 | if __name__ == '__main__': |
| 40 | logging.basicConfig(filename='output.log', level=logging.INFO) |
| 41 | SOHandler.protocol_version = "HTTP/1.0" |
| 42 | |
| 43 | httpd = HTTPServer(('', DEFAULT_PORT), SOHandler) |
| 44 | logging.info("serving on: " + str(httpd.socket.getsockname())) |
| 45 | httpd.serve_forever() |