-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver-basic.py
95 lines (72 loc) · 2.48 KB
/
server-basic.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
import json
import subprocess
import time
from urllib.parse import quote
import socket
from datetime import datetime
port = 8000
hostname=socket.gethostname()
ipAddr = socket.gethostbyname(hostname)
print(f"Serving from: http://{hostname}.local:{port}")
print(f"at IP: http://{ipAddr}:{port}")
''' Function to convert the post data to an array for easier use'''
def postDataToArray(postData):
raw_text = postData.decode("utf8")
print("Raw")
data = json.loads(raw_text)
return data
''' Handle GET and POST requests to the server'''
class uHTTPRequestHandler(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
if self.path == '/':
self.path = '/index.html'
try:
file_to_open = open(self.path[1:]).read()
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes(file_to_open, 'utf-8'))
except:
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'404 - Not Found')
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = postDataToArray(post_data)
'''
data consists of
data['action'] and
data['value']
'''
self._set_headers()
print(data)
rData = {}
rData['item'] = ""
rData['status'] = ""
if data['action'] == "getTime":
now = datetime.now()
print(now.ctime())
rData['item'] = "time"
rData['status'] = now.ctime() # a string representing the current time
self.wfile.write(bytes(json.dumps(rData), 'utf-8'))
httpd = HTTPServer(('', port), uHTTPRequestHandler)
# httpd.serve_forever()
while True:
httpd.handle_request()
time.sleep(0.1)
# while True:
# httpd.handle_request()
# now = time.localtime()
# print(f"Time: {now.tm_hour}:{now.tm_min} | {alarmTime.hr}:{alarmTime.min}")
# if (now.tm_hour == alarmTime.hr) and (now.tm_min == alarmTime.min) and not alarmOn:
# print("We have alarm!")
# alarmOn = True
# rhythmboxCommand("play")