Skip to content
Myr

use new system

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 50c39fd · Browse files · 1 file+104 added−85 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+104 added−85 removed

  • other:+104 added−85 removed

1 file+104 added−85 removed

modified:requests/models.py+104 added-85 removed
6 unmodified lines
78"""910import urllib11import urllib211import socket12import zlib13from Cookie import SimpleCookie1415from urllib2 import HTTPError16from urlparse import urlparse, urlunparse, urljoin17from datetime import datetime
4 unmodified lines
22from .packages.poster.streaminghttp import register_openers, get_handlers23from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)24from .status_codes import codes25from .exceptions import Timeout, URLRequired, TooManyRedirects, RequestException26from .monkeys import Request as _Request27from .monkeys import HTTPRedirectHandler2627from .auth import dispatch as auth_dispatch2829REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)
18 unmodified lines
48 redirect=False,49 allow_redirects=False,50 proxies=None,51 hooks=None,54 config=None):52 config=None,53 _poolmanager=None):5455 #: Float describes the timeout of the request.56 # (Use socket.setdefaulttimeout() as fallback)57 self.timeout = timeout
59 unmodified lines
117 if k not in headers:118 headers[k] = v119120 self.headers = headers121 self._poolmanager = _poolmanager122123 # Pre-request hook.124 r = dispatch_hook('pre_request', hooks, self)125 self.__dict__.update(r.__dict__)
2 unmodified lines
128 def __repr__(self):129 return '<Request [%s]>' % (self.method)130131132 def _get_opener(self):133 """Creates appropriate opener object for urllib2."""132 # def _get_opener(self):133 # """Creates appropriate opener object for urllib2."""134135 _handlers = []135 # _handlers = []136137 if self.cookies is not None:138 _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))137 # if self.cookies is not None:138 # _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))139140 if self.proxies:141 _handlers.append(urllib2.ProxyHandler(self.proxies))140 # if self.proxies:141 # _handlers.append(urllib2.ProxyHandler(self.proxies))142143 _handlers.append(HTTPRedirectHandler)143 # _handlers.append(HTTPRedirectHandler)144145 if not _handlers:146 return urllib2.urlopen145 # if not _handlers:146 # return urllib2.urlopen147148 if self.data or self.files:149 _handlers.extend(get_handlers())148 # if self.data or self.files:149 # _handlers.extend(get_handlers())150151 opener = urllib2.build_opener(*_handlers)151 # opener = urllib2.build_opener(*_handlers)152153 if self.headers:154 # Allow default headers in the opener to be overloaded155 normal_keys = [k.capitalize() for k in self.headers]156 for key, val in opener.addheaders[:]:157 if key not in normal_keys:158 continue159 # Remove it, we have a value to take its place160 opener.addheaders.remove((key, val))153 # if self.headers:154 # # Allow default headers in the opener to be overloaded155 # normal_keys = [k.capitalize() for k in self.headers]156 # for key, val in opener.addheaders[:]:157 # if key not in normal_keys:158 # continue159 # # Remove it, we have a value to take its place160 # opener.addheaders.remove((key, val))161162 return opener.open162 # return opener.open163164165 def _build_response(self, resp, is_error=False):166 """Build internal :class:`Response <Response>` object
3 unmodified lines
170171 def build(resp):172173 response = Response()174175 # Pass settings over.176 response.config = self.config175 response.status_code = getattr(resp, 'code', None)177177 try:178 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))179 response.raw = resp178 # Fallback to None if there's no staus_code, for whatever reason.179 response.status_code = getattr(resp, 'status', None)180181 if self.cookies:182 response.cookies = dict_from_cookiejar(self.cookies)181 # Make headers case-insensitive.182 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))183184 # Start off with our local cookies.185 cookies = self.cookies or dict()186185 except AttributeError:186 pass187 # Add new cookies from the server.188 if 'set-cookie' in response.headers:189 cookie_header = response.headers['set-cookie']190191 c = SimpleCookie()192 c.load(cookie_header)193194 for k,v in c.items():195 cookies.update({k: v.value})196197 # Save cookies in Response.198 response.cookies = cookies199200 # Save original resopnse for later.201 response.raw = resp202203 if is_error:204 response.error = resp205191 response.url = getattr(resp, 'url', None)206 response.url = self._build_url()207208 return response209210
7 unmodified lines
218 ('location' in r.headers) and219 ((r.status_code is codes.see_other) or (self.allow_redirects))220 ):221207 r.raw.close()222 # r.raw.close()223224 if not len(history) < self.config.get('max_redirects'):225 raise TooManyRedirects()226
26 unmodified lines
253 # params=self.params,254 auth=self.auth,255 cookies=self.cookies,256 redirect=True,242 config=self.config257 config=self.config,258 _poolmanager=self._poolmanager259 )260 request.send()261 r = request.response262263 r.history = history264265 self.response = r266 self.response.ok = True267 self.response.request = self268269270 @staticmethod
62 unmodified lines
333334 # Build the URL335 url = self._build_url()336320 # Attach uploaded files.337 # Nottin' on you.338 body = None339 content_type = None340341 from .packages.urllib3.filepost import encode_multipart_formdata342343 # Multi-part file uploads.344 if self.files:322 register_openers()345 if not isinstance(self.data, basestring):346 fields = self.data.copy()347 for (k, v) in self.files.items():348 fields.update({k: (k, v.read())})349 (body, content_type) = encode_multipart_formdata(fields)350324 # Add form-data to the multipart.325 if self.data:326 self.files.update(self.data)351 # TODO: Setup cookies.352328 data, headers = multipart_encode(self.files)353 # Add content-type if it wasn't explicitly provided.354 if (content_type) and (not 'content-type' in self.headers):355 self.headers['Content-Type'] = content_type356330 else:331 data = self._enc_data332 headers = {}357358 if self.auth:359 auth_func, auth_args = self.auth360361 r = auth_func(self, *auth_args)362363 self.__dict__.update(r.__dict__)364341 # Build the Urllib2 Request.342 req = _Request(url, data=data, headers=headers, method=self.method)365344 # Add the headers to the request.345 if self.headers:346 for k,v in self.headers.iteritems():347 req.add_header(k, v)366 conn = self._poolmanager.connection_from_url(url)367368 if not self.sent or anyway:369370 try:352 opener = self._get_opener()353 try:371 if self.cookies:372355 resp = opener(req, timeout=self.timeout)373 # Skip if 'cookie' header is explicitly set.374 if 'cookie' not in self.headers:375357 except TypeError, err:358 # timeout argument is new since Python v2.6359 if not 'timeout' in str(err):360 raise376 # Simple cookie with our dict.377 # TODO: Multi-value headers.378 c = SimpleCookie()379 c.load(self.cookies)380362 if self.config.get('timeout_fallback'):363 # fall-back and use global socket timeout (This is not thread-safe!)364 old_timeout = socket.getdefaulttimeout()365 socket.setdefaulttimeout(self.timeout)381 # Turn it into a header.382 cookie_header = c.output(header='').strip()383367 resp = opener(req)384 # Attach Cookie header to request.385 self.headers['Cookie'] = cookie_header386369 if self.config.get('timeout_fallback'):370 # restore global timeout371 socket.setdefaulttimeout(old_timeout)387 # Create the connection.388 r = conn.urlopen(389 method=self.method,390 url=url,391 body=body,392 headers=self.headers,393 redirect=False,394 assert_same_host=False,395 preload_content=False,396 decode_content=False397 )398373 if self.cookies is not None:374 self.cookies.extract_cookies(resp, req)399 # resp = {}400376 except (urllib2.HTTPError, urllib2.URLError), why:377 if hasattr(why, 'reason'):378 if isinstance(why.reason, socket.timeout):379 why = Timeout(why)380 elif isinstance(why.reason, socket.error):381 why = Timeout(why)401383 self._build_response(why, is_error=True)402 except ArithmeticError:403 pass404405 else:386 self._build_response(resp)406 self._build_response(r)407 self.response.ok = True408409 # self.sent = self.response.ok410390 self.sent = self.response.ok411 # Response manipulation hook.412 self.response = dispatch_hook('response', self.hooks, self.response)413392 # Response manipulation hook.393 self.response = dispatch_hook('response', self.hooks, self.response)414 # Post-request hook.415 r = dispatch_hook('post_request', self.hooks, self)416 self.__dict__.update(r.__dict__)417395 # Post-request hook.396 r = dispatch_hook('post_request', self.hooks, self)397 self.__dict__.update(r.__dict__)418 return self.sent419399 return self.sent420401421class Response(object):422 """The core :class:`Response <Response>` object. All423 :class:`Request <Request>` objects contain a424 :class:`response <Response>` attribute, which is an instance
125 unmodified lines