forked from juggie/AlarmServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTTPChannel.py
83 lines (73 loc) · 2.79 KB
/
HTTPChannel.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
import asyncore, asynchat
import StringIO, mimetools
import string
import os, sys
import datetime
class push_FileProducer:
# a producer which reads data from a file object
def __init__(self, file):
self.file = open(file, "rb")
def more(self):
if self.file:
data = self.file.read(2048)
if data:
return data
self.file = None
return ""
class HTTPChannel(asynchat.async_chat):
def __init__(self, server, sock, addr):
asynchat.async_chat.__init__(self, sock)
self.server = server
self.set_terminator("\r\n\r\n")
self.header = None
self.data = ""
self.shutdown = 0
def collect_incoming_data(self, data):
self.data = self.data + data
if len(self.data) > 16384:
# limit the header size to prevent attacks
self.shutdown = 1
def found_terminator(self):
if not self.header:
# parse http header
fp = StringIO.StringIO(self.data)
request = string.split(fp.readline(), None, 2)
if len(request) != 3:
# badly formed request; just shut down
self.shutdown = 1
else:
# parse message header
self.header = mimetools.Message(fp)
self.set_terminator("\r\n")
self.server.handle_request(
self, request[0], request[1], self.header
)
self.close_when_done()
self.data = ""
else:
pass # ignore body data, for now
def pushstatus(self, status, explanation="OK"):
self.push("HTTP/1.0 %d %s\r\n" % (status, explanation))
def pushok(self, content):
self.pushstatus(200, "OK")
self.push('Content-type: application/json\r\n')
self.push('Expires: Sat, 26 Jul 1997 05:00:00 GMT\r\n')
self.push('Last-Modified: '+ datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")+' GMT\r\n')
self.push('Cache-Control: no-store, no-cache, must-revalidate\r\n' )
self.push('Cache-Control: post-check=0, pre-check=0\r\n')
self.push('Pragma: no-cache\r\n' )
self.push('\r\n')
self.push(content)
def pushfile(self, file):
self.pushstatus(200, "OK")
extension = os.path.splitext(file)[1]
if extension == ".html":
self.push("Content-type: text/html\r\n")
elif extension == ".js":
self.push("Content-type: text/javascript\r\n")
elif extension == ".png":
self.push("Content-type: image/png\r\n")
elif extension == ".css":
self.push("Content-type: text/css\r\n")
self.push("\r\n")
self.push_with_producer(push_FileProducer(sys.path[0] + os.sep + 'ext' + os.sep + file))