Package restkit :: Module client
[hide private]
[frames] | no frames]

Source Code for Module restkit.client

  1  # -*- coding: utf-8 - 
  2  # 
  3  # This file is part of restkit released under the MIT license.  
  4  # See the NOTICE for more information. 
  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__) 
37 38 -class HttpResponse(object):
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
58 - def __getitem__(self, key):
59 try: 60 return getattr(self, key) 61 except AttributeError: 62 pass 63 return self.headers[key.lower()]
64
65 - def __contains__(self, key):
66 return (key.lower() in self.headers)
67
68 - def __iter__(self):
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: 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: 88 raise AlreadyRead("The response have already been read") 89 return self.response.body
90
91 - def close(self):
92 """ release the socket """ 93 self.response.body.close()
94 95 @property
96 - def body(self):
97 """ body in bytestring """ 98 return self.body_string()
99 100 body = deprecated_property( 101 body, 'body', 'use body_string() instead', 102 warning=True) 103 104 @property
105 - def body_file(self):
106 """ return body as a file like object""" 107 return self.body_stream()
108 109 body_file = deprecated_property( 110 body_file, 'body_file', 'use body_stream() instead', 111 warning=True) 112 113 @property
114 - def unicode_body(self):
115 """ like body but converted to unicode""" 116 if not self.charset: 117 raise AttributeError( 118 "You cannot access HttpResponse.unicode_body unless charset is set") 119 body = self.body_string() 120 return body.decode(self.charset, self.unicode_errors)
121 122 unicode_body = deprecated_property( 123 unicode_body, 'unicode_body', 'replaced by body_string()', 124 warning=True)
125
126 -class HttpConnection(object):
127 """ Http Connection object. """ 128 129 version = (1, 1) 130 response_class = HttpResponse 131 132
133 - def __init__(self, timeout=sock._GLOBAL_DEFAULT_TIMEOUT, 134 filters=None, follow_redirect=False, force_follow_redirect=False, 135 max_follow_redirect=MAX_FOLLOW_REDIRECTS, 136 pool_instance=None, response_class=None, 137 **ssl_args):
138 139 """ HttpConnection constructor 140 141 :param timeout: socket timeout 142 :param filters: list, list of http filters. see the doc of http filters 143 for more info 144 :param follow_redirect: boolean, by default is false. If true, 145 if the HTTP status is 301, 302 or 303 the client will follow 146 the location. 147 :param max_follow_redirect: max number of redirection. If max is reached 148 the RedirectLimit exception is raised. 149 :param pool_instance: a pool instance inherited from 150 `restkit.pool.PoolInterface` 151 :param ssl_args: ssl arguments. See http://docs.python.org/library/ssl.html 152 for more information. 153 """ 154 self._sock = None 155 self.timeout = timeout 156 self.headers = [] 157 self.req_headers = [] 158 self.ua = USER_AGENT 159 self.url = None 160 161 self.follow_redirect = follow_redirect 162 self.nb_redirections = max_follow_redirect 163 self.force_follow_redirect = force_follow_redirect 164 self.method = 'GET' 165 self.body = None 166 self.response_body = StringIO() 167 self.final_url = None 168 169 # build filter lists 170 self.filters = Filters(filters) 171 self.ssl_args = ssl_args 172 173 if not pool_instance: 174 self.should_close = True 175 self.pool = None 176 else: 177 self.pool = pool_instance 178 self.should_close = False 179 180 if response_class is not None: 181 self.response_class = response_class
182
183 - def make_connection(self):
184 """ initate a connection if needed or reuse a socket""" 185 186 # apply on connect filters 187 self.filters.apply("on_connect", self) 188 if self._sock is not None: 189 return self._sock 190 191 addr = (self.host, self.port) 192 s = None 193 # if we defined a pool use it 194 if self.pool is not None: 195 s = self.pool.get(addr) 196 197 if not s: 198 # pool is empty or we don't use a pool 199 if self.uri.scheme == "https": 200 s = sock.connect(addr, self.timeout, **self.ssl_args) 201 else: 202 s = sock.connect(addr, self.timeout) 203 return s
204
205 - def clean_connections(self):
206 sock.close(self._sock) 207 if hasattr(self.pool,'clear'): 208 self.pool.clear_host((self.host, self.port))
209
210 - def release_connection(self, address, socket):
211 if not self.pool: 212 return 213 self.pool.put(address, self._sock)
214
215 - def parse_url(self, url):
216 """ parse url and get host/port""" 217 self.uri = urlparse.urlparse(url) 218 if self.uri.scheme not in ('http', 'https'): 219 raise InvalidUrl("None valid url") 220 221 host, port = util.parse_netloc(self.uri) 222 self.host = host 223 self.port = port
224
225 - def set_body(self, body, content_type=None, content_length=None, 226 chunked=False):
227 """ set HTTP body and manage form if needed """ 228 if not body: 229 self.headers.append(('Content-Type', content_type)) 230 if self.method in ('POST', 'PUT'): 231 self.headers.append(("Content-Length", "0")) 232 return 233 234 # set content lengh if needed 235 if isinstance(body, dict): 236 if content_type is not None and \ 237 content_type.startswith("multipart/form-data"): 238 type_, opts = cgi.parse_header(content_type) 239 boundary = opts.get('boundary', uuid.uuid4().hex) 240 body, self.headers = multipart_form_encode(body, 241 self.headers, boundary) 242 else: 243 content_type = "application/x-www-form-urlencoded; charset=utf-8" 244 body = form_encode(body) 245 elif hasattr(body, "boundary"): 246 content_type = "multipart/form-data; boundary=%s" % body.boundary 247 content_length = body.get_size() 248 249 if not content_type: 250 content_type = 'application/octet-stream' 251 if hasattr(body, 'name'): 252 content_type = mimetypes.guess_type(body.name)[0] 253 254 if not content_length: 255 if hasattr(body, 'fileno'): 256 try: 257 body.flush() 258 except IOError: 259 pass 260 content_length = str(os.fstat(body.fileno())[6]) 261 elif hasattr(body, 'getvalue'): 262 try: 263 content_length = str(len(body.getvalue())) 264 except AttributeError: 265 pass 266 elif isinstance(body, types.StringTypes): 267 body = util.to_bytestring(body) 268 content_length = len(body) 269 270 if content_length: 271 self.headers.append(("Content-Length", content_length)) 272 self.headers.append(('Content-Type', content_type)) 273 274 elif not chunked: 275 raise RequestError("Can't determine content length and" + 276 "Transfer-Encoding header is not chunked") 277 278 self.body = body
279 280
281 - def request(self, url, method='GET', body=None, headers=None):
282 """ make effective request 283 284 :param url: str, url string 285 :param method: str, by default GET. http verbs 286 :param body: the body, could be a string, an iterator or a file-like object 287 :param headers: dict or list of tupple, http headers 288 """ 289 self._sock = None 290 self.url = url 291 self.final_url = url 292 self.parse_url(url) 293 self.method = method.upper() 294 self.headers = [] 295 296 # headers are better as list 297 headers = headers or [] 298 if isinstance(headers, dict): 299 headers = list(headers.items()) 300 301 ua = USER_AGENT 302 content_length = None 303 accept_encoding = 'identity' 304 chunked = False 305 content_type = None 306 307 # default host 308 try: 309 host = self.uri.netloc.encode('ascii') 310 except UnicodeEncodeError: 311 host = self.uri.netloc.encode('idna') 312 313 # normalize headers 314 for name, value in headers: 315 name = name.title() 316 if name == "User-Agent": 317 ua = value 318 elif name == "Content-Type": 319 content_type = value 320 elif name == "Content-Length": 321 content_length = str(value) 322 elif name == "Accept-Encoding": 323 accept_encoding = 'identity' 324 elif name == "Host": 325 host = value 326 elif name == "Transfer-Encoding": 327 if value.lower() == "chunked": 328 chunked = True 329 self.headers.append((name, value)) 330 else: 331 if not isinstance(value, types.StringTypes): 332 value = str(value) 333 self.headers.append((name, value)) 334 335 self.set_body(body, content_type=content_type, 336 content_length=content_length, chunked=chunked) 337 338 self.ua = ua 339 self.chunked = chunked 340 self.host_hdr = host 341 self.accept_encoding = accept_encoding 342 343 # Finally do the request 344 return self.do_send()
345
346 - def _req_headers(self):
347 # by default all connections are HTTP/1.1 348 if self.version == (1,1): 349 httpver = "HTTP/1.1" 350 else: 351 httpver = "HTTP/1.0" 352 353 # request path 354 path = self.uri.path or "/" 355 req_path = urlparse.urlunparse(('','', path, '', 356 self.uri.query, self.uri.fragment)) 357 358 # build final request headers 359 req_headers = [ 360 "%s %s %s\r\n" % (self.method, req_path, httpver), 361 "Host: %s\r\n" % self.host_hdr, 362 "User-Agent: %s\r\n" % self.ua, 363 "Accept-Encoding: %s\r\n" % self.accept_encoding 364 ] 365 req_headers.extend(["%s: %s\r\n" % (k, v) for k, v in self.headers]) 366 req_headers.append('\r\n') 367 return req_headers
368
369 - def do_send(self):
370 tries = 2 371 while True: 372 try: 373 # get socket 374 self._sock = self.make_connection() 375 376 # apply on request filters 377 self.filters.apply("on_request", self) 378 379 # build request headers 380 self.req_headers = req_headers = self._req_headers() 381 382 # send request 383 log.info('Start request: %s %s', self.method, self.url) 384 log.debug("Request headers: [%s]", req_headers) 385 386 self._sock.sendall("".join(req_headers)) 387 388 if self.body is not None: 389 if hasattr(self.body, 'read'): 390 if hasattr(self.body, 'seek'): self.body.seek(0) 391 sock.sendfile(self._sock, self.body, self.chunked) 392 elif isinstance(self.body, types.StringTypes): 393 sock.send(self._sock, self.body, self.chunked) 394 else: 395 sock.sendlines(self._sock, self.body, self.chunked) 396 397 if self.chunked: # final chunk 398 sock.send_chunk(self._sock, "") 399 400 return self.start_response() 401 except socket.gaierror, e: 402 self.clean_connections() 403 raise 404 except socket.error, e: 405 if e[0] not in (errno.EAGAIN, errno.ECONNABORTED, errno.EPIPE, 406 errno.ECONNREFUSED) or tries <= 0: 407 self.clean_connections() 408 raise 409 if e[0] == errno.EPIPE: 410 log.debug("Got EPIPE") 411 self.clean_connections() 412 except: 413 if tries <= 0: 414 raise 415 # we don't know what happend. 416 self.clean_connections() 417 time.sleep(0.2) 418 tries -= 1
419 420
421 - def do_redirect(self, response, location):
422 """ follow redirections if needed""" 423 if self.nb_redirections <= 0: 424 raise RedirectLimit("Redirection limit is reached") 425 426 if not location: 427 raise RequestError('no Location header') 428 429 new_uri = urlparse.urlparse(location) 430 if not new_uri.netloc: # we got a relative url 431 absolute_uri = "%s://%s" % (self.uri.scheme, self.uri.netloc) 432 location = urlparse.urljoin(absolute_uri, location) 433 434 log.debug("Redirect to %s" % location) 435 436 self.final_url = location 437 response.body.read() 438 self.nb_redirections -= 1 439 sock.close(self._sock) 440 return self.request(location, self.method, self.body, self.headers)
441
442 - def start_response(self):
443 """ 444 Get headers, set Body object and return HttpResponse 445 """ 446 # read headers 447 parser = http.ResponseParser(self._sock, 448 release_source = lambda:self.release_connection( 449 self.uri.netloc, self._sock)) 450 resp = parser.next() 451 452 log.debug("Start response: %s", resp.status) 453 log.debug("Response headers: [%s]", resp.headers) 454 455 location = None 456 for hdr_name, hdr_value in resp.headers: 457 if hdr_name.lower() == "location": 458 location = hdr_value 459 break 460 461 if self.follow_redirect: 462 if resp.status_int in (301, 302, 307): 463 if self.method in ('GET', 'HEAD') or \ 464 self.force_follow_redirect: 465 if self.method not in ('GET', 'HEAD') and \ 466 hasattr(self.body, 'seek'): 467 self.body.seek(0) 468 return self.do_redirect(resp, location) 469 elif resp.status_int == 303 and self.method in ('GET', 470 'HEAD'): 471 # only 'GET' is possible with this status 472 # according the rfc 473 return self.do_redirect(resp, location) 474 475 476 # apply on response filters 477 self.filters.apply("on_response", self) 478 479 self.final_url = location or self.final_url 480 log.debug("Return response: %s" % self.final_url) 481 if self.method == "HEAD": 482 resp.body = StringIO() 483 484 return self.response_class(resp, self.final_url)
485