-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsample_server.py
More file actions
62 lines (47 loc) · 1.57 KB
/
sample_server.py
File metadata and controls
62 lines (47 loc) · 1.57 KB
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
59
60
61
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class MyHandler(BaseHTTPRequestHandler):
def _set_response(self, code):
self.send_response(code)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_GET(self):
# example: this is how you get path and command
print(self.path)
print(self.command)
# example: returning an object as JSON
data = {
"row": "sample_a",
"data": [
{
"value": "data_a",
"time": "1234"
}
]
}
data_json = json.dumps(data)
self._set_response(200)
self.wfile.write(data_json.encode("utf8"))
def do_POST(self):
# example: reading content from HTTP request
data = None
content_length = self.headers['content-length']
if content_length != None:
content_length = int(content_length)
data = self.rfile.read(content_length)
# print the content, just for you to see it =)
print(data)
self._set_response(200)
def do_DELETE(self):
# example: send just a 200
self._set_response(200)
if __name__ == "__main__":
server_address = ("localhost", 8080)
handler_class = MyHandler
server_class = HTTPServer
httpd = HTTPServer(server_address, handler_class)
print("sample server running...")
try:
httpd.serve_forever()
except KeyboardInterrupt: pass
httpd.server_close()