Message.py
7.73 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""
@author Georg Hopp
"""
from ..Message import Message as BaseMessage
class Message(BaseMessage):
START_READY = 0x01
HEADERS_READY = 0x02
BODY_READY = 0x04
METHODS = ('OPTIONS','GET','HEAD','POST','PUT','DELETE','TRACE','CONNECT')
METHOD_OPTIONS = METHODS.index('OPTIONS')
METHOD_GET = METHODS.index('GET')
METHOD_HEAD = METHODS.index('HEAD')
METHOD_POST = METHODS.index('POST')
METHOD_PUT = METHODS.index('PUT')
METHOD_DELETE = METHODS.index('DELETE')
METHOD_TRACE = METHODS.index('TRACE')
METHOD_CONNECT = METHODS.index('CONNECT')
def __init__(self, remote):
super(Message, self).__init__(remote)
self.state = 0
self._chunk_size = 0
self._chunked = False
self._headers = {}
self._body = ''
self._http = None
self._method = None
self._uri = None
self._code = None
self._message = None
"""
cleaner
=====================================================================
"""
def resetStartLine(self):
self._http = None
self._uri = None
self._code = None
self._message = None
self.state &= ~Message.START_READY
def resetHeaders(self):
self._headers = {}
self.state &= ~Message.HEADERS_READY
def resetBody(self):
self._body = ''
self.state &= ~Message.BODY_READY
self._chunked = False
self._chunk_size = 0
def reset(self):
self.resetStartLine()
self.resetHeaders()
self.resetBody()
def removeHeadersByKey(self, key):
"""
Remove HTTP headers to a given key. This will remove all headers right
now associated to that key. Keys are alwasys stored lower case and
cenverted to title case during composition.
returns None
@key: str The header key to remove.
"""
if key.lower() in self._headers:
del(self._headers[key.lower()])
def removeHeader(self, header):
"""
Remove a header.
returns None
@header: tuple Holds key and value of the header to remove.
"""
key = header[0].lower()
if key in self._headers:
if header[1] in self._headers[key]:
self._headers[key].remove(header[1])
"""
setter
=====================================================================
"""
def setRequestLine(self, method, uri, http):
if self.isResponse():
raise Exception('try to make a request from a response')
self._method = method
self._uri = uri
self._http = http
def setStateLine(self, http, code, message):
if self.isRequest():
raise Exception('try to make a response from a request')
self._http = http
self._code = code
self._message = message
def setHeader(self, key, value):
"""
Add a header to the message.
Under some circumstances HTTP allows to have multiple headers with
the same key. Thats the reason why the values are handled in a list
here.
Returns None
key: The header key (The part before the colon :).
value: The header value (The part behind the colon :).
Value might also be a list a values for this key.
"""
key = key.lower()
if key in self._headers:
self._headers[key] += [v.strip() for v in value.split(',')
if v.strip() not in self._headers[key]]
else:
self._headers[key.lower()] = [v.strip() for v in value.split(',')]
def replaceHeader(self, key, value):
self._headers[key.lower()] = [v.strip() for v in value.split(',')]
def setHeaders(self, headers):
"""
This sets a bunch of headers at once. It will add the headers and not
override anything. It is neccessary to clear the headers before calling
this if only the headers given here should be in the message.
Returns None
headers: Either a list of tuples [(key,value),...] or
a dictionary {key:value,...}.
In both cases the values should be a list again.
"""
if type(headers) == dict:
headers = headers.items()
for h in headers:
self.setHeader(h[0], h[1])
def setBody(self, data):
"""
Set the body of a message. Currently we do not support sending
chunked message so this is simple...
Returns None
data: The data to set in the message body.
"""
self.replaceHeader('Content-Length', '%d'%len(data))
self._body = data
"""
getter
=====================================================================
"""
def getHttpVersion(self):
return self._http
def getMethod(self):
return self._method
def getUri(self):
return self._uri
def getResponseCode(self):
return self._code
def getResponseMessage(self):
return self._message
def getStartLine(self):
line = ''
if self.isRequest():
method = Message.METHODS[self._method]
line = ' '.join((method, self._uri, self._http))
elif self.isResponse():
line = ' '.join((self._http, str(self._code), self._message))
return line
def getHeaders(self):
return [(k, self.getHeader(k)) for k in self._headers]
def getHeader(self, key):
"""
Get all values currently associated to this header key.
returns list All values to the given key.
@key: str The key to get values for.
"""
key = key.lower()
if key not in self._headers: return ''
return ', '.join(self._headers[key])
def getBody(self):
return self._body
"""
checker
=====================================================================
"""
def headerKeyExists(self, key):
return key.lower() in self._headers
def startlineReady(self):
return Message.START_READY == self.state & Message.START_READY
def headersReady(self):
return Message.HEADERS_READY == self.state & Message.HEADERS_READY
def bodyReady(self):
return Message.BODY_READY == self.state & Message.BODY_READY
def ready(self):
return self.headersReady() and self.bodyReady()
def isRequest(self):
return self._method is not None
def isResponse(self):
return self._code is not None
def isCloseMessage(self):
if self.isRequest():
# HTTP always expects a response to be send, so a request is
# never the close message.
return False
else:
con_header = self.getHeader('Connection').lower()
if self._http == 'HTTP/1.0':
return 'keep-alive' not in con_header
else:
return 'close' in con_header
def isUpgradeMessage(self):
con_header = self.getHeader('Connection').lower()
return 'upgrade' in con_header
def isOptions(self):
return Message.METHOD_OPTIONS == self.getMethod()
def isGet(self):
return Message.METHOD_GET == self.getMethod()
def isHead(self):
return Message.METHOD_HEAD == self.getMethod()
def isPost(self):
return Message.METHOD_POST == self.getMethod()
def isPut(self):
return Message.METHOD_PUT == self.getMethod()
def isDelete(self):
return Message.METHOD_DELETE == self.getMethod()
def isTrace(self):
return Message.METHOD_TRACE == self.getMethod()
def isConnect(self):
return Message.METHOD_CONNECT == self.getMethod()
# vim: set ft=python et ts=8 sw=4 sts=4: