Last active
March 21, 2022 09:22
-
-
Save h3xagn/bc1846628cdda16ab1b900463b6ef056 to your computer and use it in GitHub Desktop.
Build ETL from device to cloud: https://h3xagn.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from http.server import HTTPServer, BaseHTTPRequestHandler | |
| import ssl | |
| import json | |
| from datetime import datetime | |
| import logging | |
| logging.basicConfig(filename="webserver.log", level=logging.DEBUG) | |
| class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): | |
| def do_POST(self): | |
| print(f"\nNew POST received at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}. Processing...") | |
| logging.info(f"New POST received at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}. Processing...") | |
| try: | |
| content_length = int(self.headers["Content-Length"]) | |
| body = self.rfile.read(content_length) | |
| self.send_response(200) | |
| self.end_headers() | |
| print(f"- Sent response 200 OK. IP: {self.client_address[0]}") | |
| logging.info(f"Sent response 200 OK. IP: {self.client_address[0]}") | |
| except: | |
| print(f"- ERROR: Could not send response.") | |
| logging.error(f"Could not send response.") | |
| try: | |
| json_string = body.decode("utf8").replace("'", '"') | |
| data = json.loads(json_string) | |
| filename = f"./data/data_{data['sn']}_{self.client_address[0].replace('.', '-')}_{datetime.now().timestamp()}.json" | |
| with open(filename, "w") as jsonfile: | |
| json.dump(data, jsonfile) | |
| print(f"- JSON data saved: {filename}.") | |
| print(f"Done.") | |
| logging.info(f"JSON data saved: {filename}.") | |
| except: | |
| print(f"- ERROR: Could save JSON file.") | |
| logging.error(f"Could save JSON file.") | |
| print("Server started. Ready.") | |
| httpd = HTTPServer(("127.0.0.1", 8443), SimpleHTTPRequestHandler) | |
| httpd.socket = ssl.wrap_socket( | |
| httpd.socket, | |
| keyfile="./cert/key.pem", | |
| certfile="./cert/certificate.pem", | |
| server_side=True, | |
| ) | |
| httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment