-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.py
86 lines (62 loc) · 1.76 KB
/
response.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
class Response:
def __init__(self, conn):
self.headers = []
self.conn = conn
pass
def setStatus(self, code, status):
status_header = "HTTP/1.1 " + `code` + " " + status + "\r\n"
self.headers.insert(0, status_header)
return
def setHeader(self, header):
self.headers.append(header + "\r\n")
return
def appendHeaderTo(self, body):
res_string = "".join(self.headers) + "\r\n" + body
self.headers = []
return res_string
def sendTest(self):
self.setStatus(200, "OK")
self.setHeader("Content-Type:text/html")
body = "<b> Hola! </b>"
self.conn.sendall(self.appendHeaderTo(body))
def sendNotFound(self, path=None):
self.setStatus(404, "Not Found")
self.setHeader("Content-Type:text/html")
body = "<h1> 404 - Not Found </h1><b>Requested Resouce Not Found</b>"
if path != None:
try:
f = open(path, 'r')
body = reduce(lambda a, b: a.strip() + b.strip(), f.readlines())
except IOError:
pass
self.conn.sendall(self.appendHeaderTo(body))
def sendHtml(self, path):
try:
f = open(path, 'r')
body = f.read()
f.close()
self.setStatus(200, "OK")
self.setHeader("Content-Type:text/html")
self.conn.sendall(self.appendHeaderTo(body))
except IOError:
return self.sendNotFound('./www/error.html')
def sendPng(self, path):
try:
f = open(path, 'r')
body = f.read()
f.close()
self.setStatus(200, "OK")
self.setHeader("Content-Type:image/png")
self.conn.sendall(self.appendHeaderTo(body))
except:
self.sendNotFound('./www/error.html')
def sendCss(self, path):
try:
f = open(path, 'r')
body = f.read()
f.close()
self.setStatus(200, "OK")
self.setHeader("Content-Type:text/css")
self.conn.sendall(self.appendHeaderTo(body))
except:
self.sendNotFound('./www/error.html')