-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
utils.py
327 lines (275 loc) · 10.1 KB
/
utils.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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import urlparse
import httplib_fork as httplib
from ws4py.client.threadedclient import WebSocketClient
import Queue
import socket
import re
class HttpResponse:
def __init__(self, method, url,
headers={}, body=None, async=False, load=True):
headers = headers.copy()
u = urlparse.urlparse(url)
kwargs = {'timeout': 1.0}
if u.scheme == 'http':
conn = httplib.HTTPConnection(u.netloc, **kwargs)
elif u.scheme == 'https':
conn = httplib.HTTPSConnection(u.netloc, **kwargs)
else:
assert False, "Unsupported scheme " + u.scheme
assert u.fragment == ''
path = u.path + ('?' + u.query if u.query else '')
self.conn = conn
if not body:
if method is 'POST':
# The spec says: "Applications SHOULD use this field
# to indicate the transfer-length of the message-body,
# unless this is prohibited by the rules in section
# 4.4."
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
# While httplib sets it only if there is body.
headers['Content-Length'] = 0
conn.request(method, path, headers=headers)
else:
if isinstance(body, unicode):
body = body.encode('utf-8')
conn.request(method, path, headers=headers, body=body)
if load:
if not async:
self._load()
else:
self._async_load()
def _get_status(self):
return self.res.status
status = property(_get_status)
def __getitem__(self, key):
return self.headers.get(key.lower())
def _load(self):
# That works for Content-Length responses.
self.res = self.conn.getresponse()
self.headers = dict( (k.lower(), v) for k, v in self.res.getheaders() )
self.body = self.res.read()
self.close()
def close(self):
if self.conn:
self.conn.close()
self.conn = None
def _async_load(self):
# That works for Transfer-Encoding: Chunked
self.res = self.conn.getresponse()
self.headers = dict( (k.lower(), v) for k, v in self.res.getheaders() )
def read(self):
data = self.res.read(10240)
if data:
return data
else:
self.close()
return None
def old_POST_async(url, **kwargs):
return HttpResponse('POST', url, async=True, **kwargs)
class WebSocket8Client(object):
class ConnectionClosedException(Exception): pass
def __init__(self, url):
queue = Queue.Queue()
self.queue = queue
class IntWebSocketClient(WebSocketClient):
def received_message(self, m):
queue.put(unicode(str(m), 'utf-8'))
def closed(self, code, reason):
queue.put((code, reason))
# def read_from_connection(self, amount):
# r = super(IntWebSocketClient, self).read_from_connection(amount)
# if self.stream.closing:
# queue.put((self.stream.closing.code, self.stream.closing.reason[2:]))
# elif not r:
# queue.put((1000, ""))
# return r
self.client = IntWebSocketClient(url)
self.client.connect()
def close(self):
if self.client:
self.client.running = False
self.client.close()
self.client._th.join()
self.client = None
def send(self, data):
self.client.send(data)
def recv(self):
try:
r = self.queue.get(timeout=1.0)
if isinstance(r, tuple):
ce = self.ConnectionClosedException()
(ce.code, ce.reason) = r
raise ce
return r
except:
self.close()
raise
def recvline(s):
b = []
c = None
while c != '\n':
c = s.recv(1)
b.append( c )
return ''.join(b)
class CaseInsensitiveDict(object):
def __init__(self, *args, **kwargs):
self.lower = {}
self.d = dict(*args, **kwargs)
for k in self.d:
self[k] = self.d[k]
def __getitem__(self, key, *args, **kwargs):
pkey = self.lower.setdefault(key.lower(), key)
return self.d.__getitem__(pkey, *args, **kwargs)
def __setitem__(self, key, *args, **kwargs):
pkey = self.lower.setdefault(key.lower(), key)
return self.d.__setitem__(pkey, *args, **kwargs)
def items(self):
for k in self.lower.values():
yield (k, self[k])
def __repr__(self): return repr(self.d)
def __str__(self): return str(self.d)
def get(self, key, *args, **kwargs):
pkey = self.lower.setdefault(key.lower(), key)
return self.d.get(pkey, *args, **kwargs)
def __contains__(self, key):
pkey = self.lower.setdefault(key.lower(), key)
return pkey in self.d
class Response(object):
def __repr__(self):
return '<Response HTTP/%s %s %r %r>' % (
self.http, self.status, self.description, self.headers)
def __str__(self): return repr(self)
def __getitem__(self, key):
return self.headers.get(key)
def get(self, key, default):
return self.headers.get(key, default)
class RawHttpConnection(object):
def __init__(self, url):
u = urlparse.urlparse(url)
self.s = socket.create_connection((u.hostname, u.port), timeout=1)
def request(self, method, url, headers={}, body=None, timeout=1, http="1.1"):
headers = CaseInsensitiveDict(headers)
if method == 'POST':
body = (body or '').encode('utf-8')
u = urlparse.urlparse(url)
headers['Host'] = u.hostname + ':' + str(u.port) if u.port else u.hostname
if body is not None:
headers['Content-Length'] = str(len(body))
rel_url = url[ url.find(u.path): ]
req = ["%s %s HTTP/%s" % (method, rel_url, http)]
for k, v in headers.items():
req.append( "%s: %s" % (k, v) )
req.append('')
req.append('')
self.send('\r\n'.join(req))
if body:
self.send(body)
head = recvline(self.s)
r = re.match(r'HTTP/(?P<version>\S+) (?P<status>\S+) (?P<description>.*)', head)
resp = Response()
resp.http = r.group('version')
resp.status = int(r.group('status'))
resp.description = r.group('description').rstrip('\r\n')
resp.headers = CaseInsensitiveDict()
while True:
header = recvline(self.s)
if header in ['\n', '\r\n']:
break
k, _, v = header.partition(':')
resp.headers[k] = v.lstrip().rstrip('\r\n')
return resp
def read(self, size=None):
if size is None:
# A single packet by default
return self.s.recv(999999)
data = []
while size > 0:
c = self.s.recv(size)
if not c:
raise Exception('Socket closed!')
size -= len(c)
data.append( c )
return ''.join(data)
def read_till_eof(self):
data = []
while True:
c = self.s.recv(999999)
if not c:
break
data.append( c )
return ''.join(data)
def closed(self):
# To check if socket is being closed, we need to recv and see
# if the response is empty. If it is not - we're in trouble -
# abort.
t = self.s.settimeout(0.1)
r = self.s.recv(1) == ''
if not r:
raise Exception('Socket not closed!')
self.s.settimeout(t)
return r
def read_chunk(self):
line = recvline(self.s).rstrip('\r\n')
bytes = int(line, 16) + 2 # Additional \r\n
return self.read(bytes)[:-2]
def send(self, data):
self.s.sendall(data)
def close(self):
self.s.close()
def SynchronousHttpRequest(method, url, **kwargs):
c = RawHttpConnection(url)
r = c.request(method, url, **kwargs)
if r.get('Transfer-Encoding', '').lower() == 'chunked':
chunks = []
while True:
chunk = c.read_chunk()
if len(chunk) == 0:
break
chunks.append( chunk )
r.body = ''.join(chunks)
elif r.get('Content-Length', ''):
cl = int(r['Content-Length'])
r.body = c.read(cl)
elif 'close' in [k.strip() for k in r.get('Connection', '').lower().split(',')]:
r.body = c.read_till_eof()
else:
# Whitelist statuses that may not need a response
if r.status in [101, 304, 204] or (r.status == 200 and method == 'OPTIONS'):
r.body = ''
else:
raise Exception(str(r.status) + ' '+str(r.headers) + " No Transfer-Encoding:chunked nor Content-Length nor Connection:Close!")
c.close()
return r
def GET(url, **kwargs):
return SynchronousHttpRequest('GET', url, **kwargs)
def POST(url, **kwargs):
return SynchronousHttpRequest('POST', url, **kwargs)
def OPTIONS(url, **kwargs):
return SynchronousHttpRequest('OPTIONS', url, **kwargs)
def AsynchronousHttpRequest(method, url, **kwargs):
c = RawHttpConnection(url)
r = c.request(method, url, **kwargs)
if r.get('Transfer-Encoding', '').lower() == 'chunked':
def read():
return c.read_chunk()
r.read = read
elif r.get('Content-Length', ''):
cl = int(r['Content-Length'])
def read():
return c.read(cl)
r.read = read
elif ('close' in [k.strip() for k in r.get('Connection', '').lower().split(',')]
or r.status == 101):
def read():
return c.read()
r.read = read
else:
raise Exception(str(r.status) + ' '+str(r.headers) + " No Transfer-Encoding:chunked nor Content-Length nor Connection:Close!")
def close():
c.close()
r.close = close
return r
def GET_async(url, **kwargs):
return AsynchronousHttpRequest('GET', url, **kwargs)
def POST_async(url, **kwargs):
return AsynchronousHttpRequest('POST', url, **kwargs)