1
2
3
4
5
6 import cgi
7 import errno
8 import logging
9 import mimetypes
10 import os
11 import socket
12 import time
13 try:
14 from cStringIO import StringIO
15 except ImportError:
16 from StringIO import StringIO
17 import types
18 import urlparse
19 import uuid
20
21 from restkit import __version__
22 from restkit.errors import RequestError, InvalidUrl, RedirectLimit, \
23 AlreadyRead
24 from restkit.filters import Filters
25 from restkit.forms import multipart_form_encode, form_encode
26 from restkit.util import sock
27 from restkit import tee
28 from restkit import util
29 from restkit.util.misc import deprecated_property
30 from restkit import http
31
32 MAX_FOLLOW_REDIRECTS = 5
33
34 USER_AGENT = "restkit/%s" % __version__
35
36 log = logging.getLogger(__name__)
39 """ Http Response object returned by HttpConnction"""
40
41 charset = "utf8"
42 unicode_errors = 'strict'
43
44 - def __init__(self, response, final_url):
45 self.response = response
46 self.status = response.status
47 self.status_int = response.status_int
48 self.version = response.version
49 self.headerslist = response.headers
50 self.final_url = final_url
51
52 headers = {}
53 for key, value in response.headers:
54 headers[key.lower()] = value
55 self.headers = headers
56 self.closed = False
57
59 try:
60 return getattr(self, key)
61 except AttributeError:
62 pass
63 return self.headers[key.lower()]
64
66 return (key.lower() in self.headers)
67
69 for item in list(self.headers.items()):
70 yield item
71
72 - def body_string(self, charset=None, unicode_errors="strict"):
73 """ return body string, by default in bytestring """
74 if self.closed or self.response.body.closed:
75 raise AlreadyRead("The response have already been read")
76 body = self.response.body.read()
77 if charset is not None:
78 try:
79 body = body.decode(charset, unicode_errors)
80 except UnicodeDecodeError:
81 pass
82 self.close()
83 return body
84
85 - def body_stream(self):
86 """ return full body stream """
87 if self.closed or self.response.body.closed:
88 raise AlreadyRead("The response have already been read")
89 return self.response.body
90
92 """ release the socket """
93 self.closed = True
94 self.response.body.close()
95
96 @property
98 """ body in bytestring """
99 return self.body_string()
100
101 body = deprecated_property(
102 body, 'body', 'use body_string() instead',
103 warning=True)
104
105 @property
106 - def body_file(self):
107 """ return body as a file like object"""
108 return self.body_stream()
109
110 body_file = deprecated_property(
111 body_file, 'body_file', 'use body_stream() instead',
112 warning=True)
113
114 @property
115 - def unicode_body(self):
116 """ like body but converted to unicode"""
117 if not self.charset:
118 raise AttributeError(
119 "You cannot access HttpResponse.unicode_body unless charset is set")
120 body = self.body_string()
121 return body.decode(self.charset, self.unicode_errors)
122
123 unicode_body = deprecated_property(
124 unicode_body, 'unicode_body', 'replaced by body_string()',
125 warning=True)
126
128 """ Http Connection object. """
129
130 version = (1, 1)
131 response_class = HttpResponse
132
133
139
140 """ HttpConnection constructor
141
142 :param timeout: socket timeout
143 :param filters: list, list of http filters. see the doc of http filters
144 for more info
145 :param follow_redirect: boolean, by default is false. If true,
146 if the HTTP status is 301, 302 or 303 the client will follow
147 the location.
148 :param max_follow_redirect: max number of redirection. If max is reached
149 the RedirectLimit exception is raised.
150 :param pool_instance: a pool instance inherited from
151 `restkit.pool.PoolInterface`
152 :param ssl_args: ssl arguments. See http://docs.python.org/library/ssl.html
153 for more information.
154 """
155 self._sock = None
156 self.timeout = timeout
157 self.headers = []
158 self.req_headers = []
159 self.ua = USER_AGENT
160 self.url = None
161
162 self.follow_redirect = follow_redirect
163 self.nb_redirections = max_follow_redirect
164 self.force_follow_redirect = force_follow_redirect
165 self.method = 'GET'
166 self.body = None
167 self.response_body = StringIO()
168 self.final_url = None
169
170
171 self.filters = Filters(filters)
172 self.ssl_args = ssl_args or {}
173
174 if not pool_instance:
175 self.should_close = True
176 self.pool = None
177 else:
178 self.pool = pool_instance
179 self.should_close = False
180
181 if response_class is not None:
182 self.response_class = response_class
183
185 """ initate a connection if needed or reuse a socket"""
186
187
188 self.filters.apply("on_connect", self)
189 if self._sock is not None:
190 return self._sock
191
192 addr = (self.host, self.port)
193 s = None
194
195 if self.pool is not None:
196 s = self.pool.get(addr)
197
198 if not s:
199
200 if self.uri.scheme == "https":
201 s = sock.connect(addr, True, self.timeout, **self.ssl_args)
202 else:
203 s = sock.connect(addr, False, self.timeout)
204 return s
205
210
216
218 """ parse url and get host/port"""
219 self.uri = urlparse.urlparse(url)
220 if self.uri.scheme not in ('http', 'https'):
221 raise InvalidUrl("None valid url")
222
223 host, port = util.parse_netloc(self.uri)
224 self.host = host
225 self.port = port
226
227 - def set_body(self, body, content_type=None, content_length=None,
228 chunked=False):
229 """ set HTTP body and manage form if needed """
230 if not body:
231 if content_type is not None:
232 self.headers.append(('Content-Type', content_type))
233 if self.method in ('POST', 'PUT'):
234 self.headers.append(("Content-Length", "0"))
235 return
236
237
238 if isinstance(body, dict):
239 if content_type is not None and \
240 content_type.startswith("multipart/form-data"):
241 type_, opts = cgi.parse_header(content_type)
242 boundary = opts.get('boundary', uuid.uuid4().hex)
243 body, self.headers = multipart_form_encode(body,
244 self.headers, boundary)
245 else:
246 content_type = "application/x-www-form-urlencoded; charset=utf-8"
247 body = form_encode(body)
248 elif hasattr(body, "boundary"):
249 content_type = "multipart/form-data; boundary=%s" % body.boundary
250 content_length = body.get_size()
251
252 if not content_type:
253 content_type = 'application/octet-stream'
254 if hasattr(body, 'name'):
255 content_type = mimetypes.guess_type(body.name)[0]
256
257 if not content_length:
258 if hasattr(body, 'fileno'):
259 try:
260 body.flush()
261 except IOError:
262 pass
263 content_length = str(os.fstat(body.fileno())[6])
264 elif hasattr(body, 'getvalue'):
265 try:
266 content_length = str(len(body.getvalue()))
267 except AttributeError:
268 pass
269 elif isinstance(body, types.StringTypes):
270 body = util.to_bytestring(body)
271 content_length = len(body)
272
273 if content_length:
274 self.headers.append(("Content-Length", content_length))
275 if content_type is not None:
276 self.headers.append(('Content-Type', content_type))
277
278 elif not chunked:
279 raise RequestError("Can't determine content length and" +
280 "Transfer-Encoding header is not chunked")
281
282 self.body = body
283
284
285 - def request(self, url, method='GET', body=None, headers=None):
286 """ make effective request
287
288 :param url: str, url string
289 :param method: str, by default GET. http verbs
290 :param body: the body, could be a string, an iterator or a file-like object
291 :param headers: dict or list of tupple, http headers
292 """
293 self._sock = None
294 self.url = url
295 self.final_url = url
296 self.parse_url(url)
297 self.method = method.upper()
298 self.headers = []
299
300
301 headers = headers or []
302 if isinstance(headers, dict):
303 headers = list(headers.items())
304
305 ua = USER_AGENT
306 content_length = None
307 accept_encoding = 'identity'
308 chunked = False
309 content_type = None
310
311 if not self.pool:
312 connection = "close"
313 else:
314 connection = "keep-alive"
315
316
317 try:
318 host = self.uri.netloc.encode('ascii')
319 except UnicodeEncodeError:
320 host = self.uri.netloc.encode('idna')
321
322
323 for name, value in headers:
324 name = name.title()
325 if name == "User-Agent":
326 ua = value
327 elif name == "Content-Type":
328 content_type = value
329 elif name == "Content-Length":
330 content_length = str(value)
331 elif name == "Accept-Encoding":
332 accept_encoding = value
333 elif name == "Host":
334 host = value
335 elif name == "Transfer-Encoding":
336 if value.lower() == "chunked":
337 chunked = True
338 self.headers.append((name, value))
339 elif name == "Connection":
340 connection = value
341 else:
342 if not isinstance(value, types.StringTypes):
343 value = str(value)
344 self.headers.append((name, value))
345
346 self.headers.append(("Connection", connection))
347
348 self.set_body(body, content_type=content_type,
349 content_length=content_length, chunked=chunked)
350
351 self.ua = ua
352 self.chunked = chunked
353 self.host_hdr = host
354 self.accept_encoding = accept_encoding
355
356
357 return self.do_send()
358
360
361 if self.version == (1,1):
362 httpver = "HTTP/1.1"
363 else:
364 httpver = "HTTP/1.0"
365
366
367 path = self.uri.path or "/"
368 req_path = urlparse.urlunparse(('','', path, '',
369 self.uri.query, self.uri.fragment))
370
371
372 req_headers = [
373 "%s %s %s\r\n" % (self.method, req_path, httpver),
374 "Host: %s\r\n" % self.host_hdr,
375 "User-Agent: %s\r\n" % self.ua,
376 "Accept-Encoding: %s\r\n" % self.accept_encoding
377 ]
378 req_headers.extend(["%s: %s\r\n" % (k, v) for k, v in self.headers])
379 req_headers.append('\r\n')
380 return req_headers
381
383 tries = 2
384 while True:
385 try:
386
387 self._sock = self.make_connection()
388
389
390 self.filters.apply("on_request", self)
391
392
393 self.req_headers = req_headers = self._req_headers()
394
395
396 log.info('Start request: %s %s', self.method, self.url)
397 log.debug("Request headers: [%s]", req_headers)
398
399 self._sock.sendall("".join(req_headers))
400
401 if self.body is not None:
402 if hasattr(self.body, 'read'):
403 if hasattr(self.body, 'seek'): self.body.seek(0)
404 sock.sendfile(self._sock, self.body, self.chunked)
405 elif isinstance(self.body, types.StringTypes):
406 sock.send(self._sock, self.body, self.chunked)
407 else:
408 sock.sendlines(self._sock, self.body, self.chunked)
409
410 if self.chunked:
411 sock.send_chunk(self._sock, "")
412
413 return self.start_response()
414 except socket.gaierror, e:
415 self.clean_connections()
416 raise
417 except socket.error, e:
418 if e[0] not in (errno.EAGAIN, errno.ECONNABORTED, errno.EPIPE,
419 errno.ECONNREFUSED) or tries <= 0:
420 self.clean_connections()
421 raise
422 if e[0] == errno.EPIPE:
423 log.debug("Got EPIPE")
424 self.clean_connections()
425 except:
426 if tries <= 0:
427 raise
428
429 self.clean_connections()
430 time.sleep(0.2)
431 tries -= 1
432
433
435 """ follow redirections if needed"""
436 if self.nb_redirections <= 0:
437 raise RedirectLimit("Redirection limit is reached")
438
439 if not location:
440 raise RequestError('no Location header')
441
442 new_uri = urlparse.urlparse(location)
443 if not new_uri.netloc:
444 absolute_uri = "%s://%s" % (self.uri.scheme, self.uri.netloc)
445 location = urlparse.urljoin(absolute_uri, location)
446
447 log.debug("Redirect to %s" % location)
448
449 self.final_url = location
450 response.body.read()
451 self.nb_redirections -= 1
452 sock.close(self._sock)
453 return self.request(location, self.method, self.body, self.headers)
454
456 """
457 Get headers, set Body object and return HttpResponse
458 """
459
460 parser = http.ResponseParser(self._sock,
461 release_source = lambda:self.release_connection(
462 (self.host, self.port), self._sock))
463 resp = parser.next()
464
465 log.debug("Start response: %s", resp.status)
466 log.debug("Response headers: [%s]", resp.headers)
467
468 location = None
469 for hdr_name, hdr_value in resp.headers:
470 if hdr_name.lower() == "location":
471 location = hdr_value
472 break
473
474 if self.follow_redirect:
475 if resp.status_int in (301, 302, 307):
476 if self.method in ('GET', 'HEAD') or \
477 self.force_follow_redirect:
478 if self.method not in ('GET', 'HEAD') and \
479 hasattr(self.body, 'seek'):
480 self.body.seek(0)
481 return self.do_redirect(resp, location)
482 elif resp.status_int == 303 and self.method in ('GET',
483 'HEAD'):
484
485
486 return self.do_redirect(resp, location)
487
488
489
490 self.filters.apply("on_response", self)
491
492 self.final_url = location or self.final_url
493 log.debug("Return response: %s" % self.final_url)
494 if self.method == "HEAD":
495 resp.body = StringIO()
496
497 return self.response_class(resp, self.final_url)
498