-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
58 lines (44 loc) · 1.57 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#! /usr/bin/env python
from datetime import datetime as _dt
from http.server import BaseHTTPRequestHandler, HTTPServer
import platform
import json
import cgi
class Server(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_GET(self):
self._set_headers()
response = {'response_at': str(_dt.now()), 'response_by': platform.node()}
self.wfile.write(json.dumps(response).encode('utf-8'))
def do_POST(self):
ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
if ctype != 'application/json':
self.send_response(400)
self.end_headers()
return
length = int(self.headers.get('content-length'))
message = json.loads(self.rfile.read(length))
message['received_at'] = str(_dt.now())
message['received_by'] = platform.node()
self._set_headers()
self.wfile.write(json.dumps(message).encode('utf-8'))
def run(server_class=HTTPServer, handler_class=Server, port=5000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
try:
print(f'info: start HTTP on port {port}...')
httpd.serve_forever()
except KeyboardInterrupt:
httpd.server_close()
print('info: HTTP Server stoped')
except Exception as e:
print(f'error: {e}')
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()