models.py
This file
Path
requests/models.py
623 lines · 19.1 KiB · Python
Last changed by
store hooks in Request.Kenneth Reitzbefore adoption892fcd6
History of this fileTake it
1# -*- coding: utf-8 -*-23"""4requests.models5~~~~~~~~~~~~~~~67"""89import urllib10import urllib211import socket12import zlib1314from urllib2 import HTTPError15from urlparse import urlparse, urlunparse, urljoin16from datetime import datetime1718from .config import settings19from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler20from .structures import CaseInsensitiveDict21from .packages.poster.encode import multipart_encode22from .packages.poster.streaminghttp import register_openers, get_handlers23from .utils import dict_from_cookiejar24from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects25from .status_codes import codes262728REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)29303132class Request(object):33 """The :class:`Request <models.Request>` object. It carries out all functionality of34 Requests. Recommended interface is with the Requests functions.35 """3637 def __init__(self,38 url=None, headers=dict(), files=None, method=None, data=dict(),39 params=dict(), auth=None, cookiejar=None, timeout=None, redirect=False,40 allow_redirects=False, proxies=None, hooks=None):4142 #: Float describ the timeout of the request.43 # (Use socket.setdefaulttimeout() as fallback)44 self.timeout = timeout4546 #: Request URL.47 self.url = url4849 #: Dictonary of HTTP Headers to attach to the :class:`Request <models.Request>`.50 self.headers = headers5152 #: Dictionary of files to multipart upload (``{filename: content}``).53 self.files = files5455 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.56 self.method = method5758 #: Dictionary or byte of request body data to attach to the59 #: :class:`Request <models.Request>`.60 self.data = None6162 #: Dictionary or byte of querystring data to attach to the63 #: :class:`Request <models.Request>`.64 self.params = None6566 #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history67 #: and HTTPError storage).68 self.redirect = redirect6970 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)71 self.allow_redirects = allow_redirects7273 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})74 self.proxies = proxies7576 self.data, self._enc_data = self._encode_params(data)77 self.params, self._enc_params = self._encode_params(params)7879 #: :class:`Response <models.Response>` instance, containing80 #: content and metadata of HTTP Response, once :attr:`sent <send>`.81 self.response = Response()8283 if isinstance(auth, (list, tuple)):84 auth = AuthObject(*auth)85 if not auth:86 auth = auth_manager.get_auth(self.url)8788 #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.89 self.auth = auth9091 #: CookieJar to attach to :class:`Request <models.Request>`.92 self.cookiejar = cookiejar9394 #: True if Request has been sent.95 self.sent = False9697 #: Event-handling hooks.98 self.hooks = hooks99100 # Header manipulation and defaults.101102 if settings.accept_gzip:103 settings.base_headers.update({'Accept-Encoding': 'gzip'})104105 if headers:106 headers = CaseInsensitiveDict(self.headers)107 else:108 headers = CaseInsensitiveDict()109110 for (k, v) in settings.base_headers.items():111 if k not in headers:112 headers[k] = v113114 self.headers = headers115116117 def __repr__(self):118 return '<Request [%s]>' % (self.method)119120121 def _checks(self):122 """Deterministic checks for consistency."""123124 if not self.url:125 raise URLRequired126127128 def _get_opener(self):129 """Creates appropriate opener object for urllib2."""130131 _handlers = []132133 if self.cookiejar is not None:134 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))135136 if self.auth:137 if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):138 # TODO: REMOVE THIS COMPLETELY139 auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)140 self.auth.handler = self.auth.handler(auth_manager)141 auth_manager.add_auth(self.url, self.auth)142143 _handlers.append(self.auth.handler)144145 if self.proxies:146 _handlers.append(urllib2.ProxyHandler(self.proxies))147148 _handlers.append(HTTPRedirectHandler)149150 if not _handlers:151 return urllib2.urlopen152153 if self.data or self.files:154 _handlers.extend(get_handlers())155156 opener = urllib2.build_opener(*_handlers)157158 if self.headers:159 # Allow default headers in the opener to be overloaded160 normal_keys = [k.capitalize() for k in self.headers]161 for key, val in opener.addheaders[:]:162 if key not in normal_keys:163 continue164 # Remove it, we have a value to take its place165 opener.addheaders.remove((key, val))166167 return opener.open168169170 def _build_response(self, resp, is_error=False):171 """Build internal :class:`Response <models.Response>` object from given response."""172173 def build(resp):174175 response = Response()176 response.status_code = getattr(resp, 'code', None)177178 try:179 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))180 response.read = resp.read181 response._resp = resp182 response._close = resp.close183184 if self.cookiejar:185186 response.cookies = dict_from_cookiejar(self.cookiejar)187188189 except AttributeError:190 pass191192 if is_error:193 response.error = resp194195 response.url = getattr(resp, 'url', None)196197 return response198199200 history = []201202 r = build(resp)203204 if r.status_code in REDIRECT_STATI and not self.redirect:205206 while (207 ('location' in r.headers) and208 ((r.status_code is codes.see_other) or (self.allow_redirects))209 ):210211 r.close()212213 if not len(history) < settings.max_redirects:214 raise TooManyRedirects()215216 history.append(r)217218 url = r.headers['location']219220 # Handle redirection without scheme (see: RFC 1808 Section 4)221 if url.startswith('//'):222 parsed_rurl = urlparse(r.url)223 url = '%s:%s' % (parsed_rurl.scheme, url)224225 # Facilitate non-RFC2616-compliant 'location' headers226 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')227 if not urlparse(url).netloc:228 url = urljoin(r.url, urllib.quote(urllib.unquote(url)))229230 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4231 if r.status_code is codes.see_other:232 method = 'GET'233 else:234 method = self.method235236 request = Request(237 url, self.headers, self.files, method,238 self.data, self.params, self.auth, self.cookiejar,239 redirect=True240 )241 request.send()242 r = request.response243244 r.history = history245246 self.response = r247 self.response.request = self248249250 @staticmethod251 def _encode_params(data):252 """Encode parameters in a piece of data.253254 If the data supplied is a dictionary, encodes each parameter in it, and255 returns a list of tuples containing the encoded parameters, and a urlencoded256 version of that.257258 Otherwise, assumes the data is already encoded appropriately, and259 returns it twice.260261 """262 if hasattr(data, 'items'):263 result = []264 for k, vs in data.items():265 for v in isinstance(vs, list) and vs or [vs]:266 result.append((k.encode('utf-8') if isinstance(k, unicode) else k,267 v.encode('utf-8') if isinstance(v, unicode) else v))268 return result, urllib.urlencode(result, doseq=True)269 else:270 return data, data271272273 def _build_url(self):274 """Build the actual URL to use."""275276 # Support for unicode domain names and paths.277 scheme, netloc, path, params, query, fragment = urlparse(self.url)278 netloc = netloc.encode('idna')279 if isinstance(path, unicode):280 path = path.encode('utf-8')281 path = urllib.quote(urllib.unquote(path))282 self.url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))283284 if self._enc_params:285 if urlparse(self.url).query:286 return '%s&%s' % (self.url, self._enc_params)287 else:288 return '%s?%s' % (self.url, self._enc_params)289 else:290 return self.url291292293 def send(self, anyway=False):294 """Sends the request. Returns True of successful, false if not.295 If there was an HTTPError during transmission,296 self.response.status_code will contain the HTTPError code.297298 Once a request is successfully sent, `sent` will equal True.299300 :param anyway: If True, request will be sent, even if it has301 already been sent.302 """303304 self._checks()305 success = False306307 # Logging308 if settings.verbose:309 settings.verbose.write('%s %s %s\n' % (310 datetime.now().isoformat(), self.method, self.url311 ))312313314 url = self._build_url()315 if self.method in ('GET', 'HEAD', 'DELETE'):316 req = _Request(url, method=self.method)317 else:318319 if self.files:320 register_openers()321322 if self.data:323 self.files.update(self.data)324325 datagen, headers = multipart_encode(self.files)326 req = _Request(url, data=datagen, headers=headers, method=self.method)327328 else:329 req = _Request(url, data=self._enc_data, method=self.method)330331 if self.headers:332 for k,v in self.headers.iteritems():333 req.add_header(k, v)334335 if not self.sent or anyway:336337 try:338 opener = self._get_opener()339 try:340341 resp = opener(req, timeout=self.timeout)342343 except TypeError, err:344 # timeout argument is new since Python v2.6345 if not 'timeout' in str(err):346 raise347348 if settings.timeout_fallback:349 # fall-back and use global socket timeout (This is not thread-safe!)350 old_timeout = socket.getdefaulttimeout()351 socket.setdefaulttimeout(self.timeout)352353 resp = opener(req)354355 if settings.timeout_fallback:356 # restore gobal timeout357 socket.setdefaulttimeout(old_timeout)358359 if self.cookiejar is not None:360 self.cookiejar.extract_cookies(resp, req)361362 except (urllib2.HTTPError, urllib2.URLError), why:363 if hasattr(why, 'reason'):364 if isinstance(why.reason, socket.timeout):365 why = Timeout(why)366367 self._build_response(why, is_error=True)368369370 else:371 self._build_response(resp)372 self.response.ok = True373374375 self.sent = self.response.ok376377 return self.sent378379380381class Response(object):382 """The core :class:`Response <models.Response>` object. All383 :class:`Request <models.Request>` objects contain a384 :class:`response <models.Response>` attribute, which is an instance385 of this class.386 """387388 def __init__(self):389 #: Raw content of the response, in bytes.390 #: If ``content-encoding`` of response was set to ``gzip``, the391 #: response data will be automatically deflated.392 self._content = None393 #: Integer Code of responded HTTP Status.394 self.status_code = None395 #: Case-insensitive Dictionary of Response Headers.396 #: For example, ``headers['content-encoding']`` will return the397 #: value of a ``'Content-Encoding'`` response header.398 self.headers = CaseInsensitiveDict()399 #: Final URL location of Response.400 self.url = None401 #: True if no :attr:`error` occured.402 self.ok = False403 #: Resulting :class:`HTTPError` of request, if one occured.404 self.error = None405 #: A list of :class:`Response <models.Response>` objects from406 #: the history of the Request. Any redirect responses will end407 #: up here.408 self.history = []409 #: The Request that created the Response.410 self.request = None411 #: A dictionary of Cookies the server sent back.412 self.cookies = None413414415 def __repr__(self):416 return '<Response [%s]>' % (self.status_code)417418419 def __nonzero__(self):420 """Returns true if :attr:`status_code` is 'OK'."""421 return not self.error422423424 def __getattr__(self, name):425 """Read and returns the full stream when accessing to :attr: `content`"""426 if name == 'content':427 if self._content is not None:428 return self._content429 self._content = self.read()430 if self.headers.get('content-encoding', '') == 'gzip':431 try:432 self._content = zlib.decompress(self._content, 16+zlib.MAX_WBITS)433 except zlib.error:434 pass435 return self._content436 else:437 raise AttributeError438439 def raise_for_status(self):440 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""441 if self.error:442 raise self.error443444445 def close(self):446 if self._resp.fp is not None and hasattr(self._resp.fp, '_sock'):447 self._resp.fp._sock.recv = None448 self._close()449450class AuthManager(object):451 """Requests Authentication Manager."""452453 def __new__(cls):454 singleton = cls.__dict__.get('__singleton__')455 if singleton is not None:456 return singleton457458 cls.__singleton__ = singleton = object.__new__(cls)459460 return singleton461462463 def __init__(self):464 self.passwd = {}465 self._auth = {}466467468 def __repr__(self):469 return '<AuthManager [%s]>' % (self.method)470471472 def add_auth(self, uri, auth):473 """Registers AuthObject to AuthManager."""474475 uri = self.reduce_uri(uri, False)476477 # try to make it an AuthObject478 if not isinstance(auth, AuthObject):479 try:480 auth = AuthObject(*auth)481 except TypeError:482 pass483484 self._auth[uri] = auth485486487 def add_password(self, realm, uri, user, passwd):488 """Adds password to AuthManager."""489 # uri could be a single URI or a sequence490 if isinstance(uri, basestring):491 uri = [uri]492493 reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])494495 if reduced_uri not in self.passwd:496 self.passwd[reduced_uri] = {}497 self.passwd[reduced_uri] = (user, passwd)498499500 def find_user_password(self, realm, authuri):501 for uris, authinfo in self.passwd.iteritems():502 reduced_authuri = self.reduce_uri(authuri, False)503 for uri in uris:504 if self.is_suburi(uri, reduced_authuri):505 return authinfo506507 return (None, None)508509510 def get_auth(self, uri):511 (in_domain, in_path) = self.reduce_uri(uri, False)512513 for domain, path, authority in (514 (i[0][0], i[0][1], i[1]) for i in self._auth.iteritems()515 ):516 if in_domain == domain:517 if path in in_path:518 return authority519520521 def reduce_uri(self, uri, default_port=True):522 """Accept authority or URI and extract only the authority and path."""523524 # note HTTP URLs do not have a userinfo component525 parts = urllib2.urlparse.urlsplit(uri)526527 if parts[1]:528 # URI529 scheme = parts[0]530 authority = parts[1]531 path = parts[2] or '/'532 else:533 # host or host:port534 scheme = None535 authority = uri536 path = '/'537538 host, port = urllib2.splitport(authority)539540 if default_port and port is None and scheme is not None:541 dport = {"http": 80,542 "https": 443,543 }.get(scheme)544 if dport is not None:545 authority = "%s:%d" % (host, dport)546547 return authority, path548549550 def is_suburi(self, base, test):551 """Check if test is below base in a URI tree552553 Both args must be URIs in reduced form.554 """555 if base == test:556 return True557 if base[0] != test[0]:558 return False559 common = urllib2.posixpath.commonprefix((base[1], test[1]))560 if len(common) == len(base[1]):561 return True562 return False563564565 def empty(self):566 self.passwd = {}567568569 def remove(self, uri, realm=None):570 # uri could be a single URI or a sequence571 if isinstance(uri, basestring):572 uri = [uri]573574 for default_port in True, False:575 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])576 del self.passwd[reduced_uri][realm]577578579 def __contains__(self, uri):580 # uri could be a single URI or a sequence581 if isinstance(uri, basestring):582 uri = [uri]583584 uri = tuple([self.reduce_uri(u, False) for u in uri])585586 if uri in self.passwd:587 return True588589 return False590591auth_manager = AuthManager()592593594595class AuthObject(object):596 """The :class:`AuthObject` is a simple HTTP Authentication token. When597 given to a Requests function, it enables Basic HTTP Authentication for that598 Request. You can also enable Authorization for domain realms with AutoAuth.599 See AutoAuth for more details.600601 :param username: Username to authenticate with.602 :param password: Password for given username.603 :param realm: (optional) the realm this auth applies to604 :param handler: (optional) basic || digest || proxy_basic || proxy_digest605 """606607 _handlers = {608 'basic': HTTPBasicAuthHandler,609 'forced_basic': HTTPForcedBasicAuthHandler,610 'digest': HTTPDigestAuthHandler,611 'proxy_basic': urllib2.ProxyBasicAuthHandler,612 'proxy_digest': urllib2.ProxyDigestAuthHandler613 }614615 def __init__(self, username, password, handler='forced_basic', realm=None):616 self.username = username617 self.password = password618 self.realm = realm619620 if isinstance(handler, basestring):621 self.handler = self._handlers.get(handler.lower(), HTTPForcedBasicAuthHandler)622 else:623 self.handler = handler