-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
86 lines (69 loc) · 2.93 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
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
import os
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qsl
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
# print("GET Request")
# insert relevant code
parsed = urlparse(self.path)
# Check for content.html
if parsed.path in ['/content.html']:
# retrieve HTML file
fp = open('.'+self.path)
content = fp.read()
# generate headers
self.send_response(200) # OK
self.send_header("Content-type", "text/html")
self.send_header("Content-length", len(content))
self.end_headers()
# Send to browser
self.wfile.write(bytes(content, "utf-8"))
fp.close()
elif parsed.path.__contains__('.png'):
# retrieve image
filename = parsed.path[1:]
if os.path.exists(filename):
with open(filename, 'rb') as fp:
content = fp.read()
self.send_response(200) #OK
self.send_header("Content-type", "image/png")
self.send_header("Content-length", len(content))
self.end_headers()
# send to browser
self.wfile.write(bytes(content))
elif parsed.path.__contains__('.jpg') or parsed.path.__contains__('.jpeg'):
# retrieve image
filename = parsed.path[1:]
if os.path.exists(filename):
with open(filename, 'rb') as fp:
content = fp.read()
self.send_response(200) # OK
self.send_header("Content-type", "image/jpeg")
self.send_header("Content-length", len(content))
self.end_headers()
# Send to browser
self.wfile.write(bytes(content))
elif parsed.path.__contains__('.mp4'):
# retrieve video
filename = parsed.path[1:]
if os.path.exists(filename):
with open(filename, 'rb') as fp:
content = fp.read()
self.send_response(200) # OK
self.send_header("Content-type", "video/mp4")
self.send_header("Content-length", len(content))
self.end_headers()
# Send to browser
self.wfile.write(bytes(content))
else:
# generate 404 for GET requests that aren't the 3 files above
self.send_response(404)
self.end_headers()
self.wfile.write(bytes("404: %s not found" % self.path, "utf-8"))
def do_POST(self):
print("POST Request")
# insert relevant code
if __name__ == "__main__":
httpd = HTTPServer(('localhost', 5000), MyHandler)
print("Server listing in port: ", 5000)
httpd.serve_forever()