WHOOOOOOOOOOOOOOOO
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 c6183d2 · Browse files · 4 files·+538 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+538 added−35 removed
- other:+538 added−35 removed
Provenance
- Commit
92d5703- Tree
e18a32b- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
c6183d2
4 files changed+538 added−35 removed
modified:requests/adapters.py-2 removed
115 unmodified lines116 # extract_cookies_to_jar(self.cookies, self, resp)117 118 119 120-121-120 def close(self):121 """Dispose of any internal state.122 123 Currently, this just closes the PoolManager, which closes pooled51 unmodified linesmodified:requests/api.py+2 added-5 removed
43 unmodified lines44 if session is None:45 session = sessions.session(config=kwargs.get('config', None))46 adhoc_session = True47 48- try:49- return session.request(method=method, url=url, **kwargs)50- finally:51- if adhoc_session:52- session.close()48 49+ return session.request(method=method, url=url, **kwargs)50 51+52 def get(url, **kwargs):53 """Sends a GET request. Returns :class:`Response` object.54 55 :param url: URL for the new :class:`Request` object.70 unmodified linesmodified:requests/models.py+492 added-2 removed
15 unmodified lines16 from datetime import datetime17 from io import BytesIO18 19 from .hooks import dispatch_hook, HOOKS20-zz20+from .structures import CaseInsensitiveDict21 from .status_codes import codes22 23 from .auth import HTTPBasicAuth, HTTPProxyAuth24 from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header146 unmodified lines171 self.data = data172 self.params = params173 self.auth = auth174 self.cookies = cookies175- self.timeout = timeout175+ # self.timeout = timeout176 # TODO: move to attached177 self.allow_redirects = allow_redirects178 self.proxies = proxies179 self.hooks = hooks178 unmodified lines358 cookie_header = get_cookie_header(cookies, self)359 if cookie_header is not None:360 self.headers['Cookie'] = cookie_header361 362+ def send(self):363+ pass364+ # return365 366+ # def prepare_allow_367+368+369+370+class OldRequest(object):371+ """The :class:`Request <Request>` object. It carries out all functionality372+ of Requests. Recommended interface is with the Requests functions.373+ """374+375+ def __init__(self,376+ url=None,377+ headers=dict(),378+ files=None,379+ method=None,380+ data=dict(),381+ params=dict(),382+ auth=None,383+ cookies=None,384+ timeout=None,385+ redirect=False,386+ allow_redirects=False,387+ proxies=None,388+ hooks=None,389+ config=None,390+ prefetch=True,391+ _poolmanager=None,392+ verify=None,393+ session=None,394+ cert=None):395+396+ #: Dictionary of configurations for this request.397+ self.config = dict(config or [])398+399+ #: Float describes the timeout of the request.400+ # (Use socket.setdefaulttimeout() as fallback)401+ self.timeout = timeout402+403+ # URL404+405+ #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.406+ self.headers = dict(headers or [])407+408+ #: Dictionary of files to multipart upload (``{filename: content}``).409+ self.files = None410+411+ #: HTTP Method to use.412+ self.method = method413+414+ #: Dictionary, bytes or file stream of request body data to attach to the415+ #: :class:`Request <Request>`.416+ self.data = None417+418+ #: Dictionary of querystring data to attach to the419+ #: :class:`Request <Request>`. The dictionary values can be lists for representing420+ #: multivalued query parameters.421+ self.params = None422+423+ #: True if :class:`Request <Request>` is part of a redirect chain (disables history424+ #: and HTTPError storage).425+ self.redirect = redirect426+427+ #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)428+ self.allow_redirects = allow_redirects429+430+ # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})431+ self.proxies = dict(proxies or [])432+433+ for proxy_type, uri_ref in list(self.proxies.items()):434+ if not uri_ref:435+ del self.proxies[proxy_type]436+437+ # If no proxies are given, allow configuration by environment variables438+ # HTTP_PROXY and HTTPS_PROXY.439+ if not self.proxies and self.config.get('trust_env'):440+ self.proxies = get_environ_proxies(self.url)441+442+ self.data = data443+ self.params = params444+ self.files = files445+446+ #: :class:`Response <Response>` instance, containing447+ #: content and metadata of HTTP Response, once :attr:`sent <send>`.448+ self.response = Response()449+450+ #: Authentication tuple or object to attach to :class:`Request <Request>`.451+ self.auth = auth452+453+ # #: CookieJar to attach to :class:`Request <Request>`.454+ # if isinstance(cookies, cookielib.CookieJar):455+ # self.cookies = cookies456+ # else:457+ # self.cookies = cookiejar_from_dict(cookies)458+459+ #: True if Request has been sent.460+ self.sent = False461+462+ #: Event-handling hooks.463+ self.hooks = {}464+465+ for event in HOOKS:466+ self.hooks[event] = []467+468+ hooks = hooks or {}469+470+ for (k, v) in list(hooks.items()):471+ self.register_hook(event=k, hook=v)472+473+ #: Session.474+ self.session = session475+476+ #: SSL Verification.477+ self.verify = verify478+479+ #: SSL Certificate480+ self.cert = cert481+482+ #: Prefetch response content483+ self.prefetch = prefetch484+485+ # if headers:486+ # headers = CaseInsensitiveDict(self.headers)487+ # else:488+ # headers = CaseInsensitiveDict()489+490+ # Add configured base headers.491+ for (k, v) in list(self.config.get('base_headers', {}).items()):492+ if k not in headers:493+ headers[k] = v494+495+ self.headers = headers496+ self._poolmanager = _poolmanager497+498+ def __repr__(self):499+ return '<Request [%s]>' % (self.method)500+501+ def _build_response(self, resp):502+ """Build internal :class:`Response <Response>` object503+ from given response.504+ """505+506+ def build(resp):507+508+ response = Response()509+510+ # Pass settings over.511+ response.config = self.config512+513+ if resp:514+515+ # Fallback to None if there's no status_code, for whatever reason.516+ # response.status_code = getattr(resp, 'status', None)517+518+ # Make headers case-insensitive.519+ # response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))520+521+ # Set encoding.522+ # response.encoding = get_encoding_from_headers(response.headers)523+524+ # Add new cookies from the server.525+ extract_cookies_to_jar(self.cookies, self, resp)526+527+ # Save cookies in Response.528+ response.cookies = self.cookies529+530+ # Save cookies in Session.531+ for cookie in self.cookies:532+ self.session.cookies.set_cookie(cookie)533+534+ # No exceptions were harmed in the making of this request.535+ response.error = getattr(resp, 'error', None)536+537+ # Save original response for later.538+ response.raw = resp539+ if isinstance(self.full_url, bytes):540+ response.url = self.full_url.decode('utf-8')541+ else:542+ response.url = self.full_url543+544+ return response545+546+ history = []547+548+ r = build(resp)549+ # TODO: session level shit550+ if r.status_code in REDIRECT_STATI and not self.redirect:551+552+ while (('location' in r.headers and r.status_code in REDIRECT_STATI) and553+ ((r.status_code is codes.see_other) or (self.allow_redirects))):554+555+ r.content # Consume socket so it can be released556+557+ if not len(history) < self.config.get('max_redirects'):558+ raise TooManyRedirects()559+560+ # Release the connection back into the pool.561+ r.raw.release_conn()562+563+ history.append(r)564+565+ url = r.headers['location']566+ data = self.data567+ files = self.files568+569+ # Handle redirection without scheme (see: RFC 1808 Section 4)570+ if url.startswith('//'):571+ parsed_rurl = urlparse(r.url)572+ url = '%s:%s' % (parsed_rurl.scheme, url)573+574+ # Facilitate non-RFC2616-compliant 'location' headers575+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')576+ if not urlparse(url).netloc:577+ url = urljoin(r.url,578+ # Compliant with RFC3986, we percent579+ # encode the url.580+ requote_uri(url))581+582+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4583+ if r.status_code is codes.see_other:584+ method = 'GET'585+ data = None586+ files = None587+ else:588+ method = self.method589+590+ # Do what the browsers do, despite standards...591+ if r.status_code in (codes.moved, codes.found) and self.method == 'POST':592+ method = 'GET'593+ data = None594+ files = None595+596+ if (r.status_code == 303) and self.method != 'HEAD':597+ method = 'GET'598+ data = None599+ files = None600+601+ # Remove the cookie headers that were sent.602+ headers = self.headers603+ try:604+ del headers['Cookie']605+ except KeyError:606+ pass607+608+ request = Request(609+ url=url,610+ headers=headers,611+ files=files,612+ method=method,613+ params=self.session.params,614+ auth=self.auth,615+ cookies=self.cookies,616+ redirect=True,617+ data=data,618+ config=self.config,619+ timeout=self.timeout,620+ _poolmanager=self._poolmanager,621+ proxies=self.proxies,622+ verify=self.verify,623+ session=self.session,624+ cert=self.cert,625+ prefetch=self.prefetch626+ )627+628+ request.send()629+ r = request.response630+631+ r.history = history632+633+ self.response = r634+ self.response.request = self635+636+637+ def register_hook(self, event, hook):638+ """Properly register a hook."""639+ if isinstance(hook, collections.Callable):640+ self.hooks[event].append(hook)641+ elif hasattr(hook, '__iter__'):642+ self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))643+644+ def deregister_hook(self, event, hook):645+ """Deregister a previously registered hook.646+ Returns True if the hook existed, False if not.647+ """648+649+ try:650+ self.hooks[event].remove(hook)651+ return True652+ except ValueError:653+ return False654+655+ def send(self, anyway=False, prefetch=None):656+ """Sends the request. Returns True if successful, False if not.657+ If there was an HTTPError during transmission,658+ self.response.status_code will contain the HTTPError code.659+660+ Once a request is successfully sent, `sent` will equal True.661+662+ :param anyway: If True, request will be sent, even if it has663+ already been sent.664+665+ :param prefetch: If not None, will override the request's own setting666+ for prefetch.667+ """668+669+ # Build the URL670+ url = self.full_url671+672+ # Pre-request hook.673+ r = dispatch_hook('pre_request', self.hooks, self)674+ self.__dict__.update(r.__dict__)675+676+ # Logging677+ log.info('Sending %s: %s' % (self, url))678+679+ # Use .netrc auth if none was provided.680+ if not self.auth and self.config.get('trust_env'):681+ self.auth = get_netrc_auth(url)682+683+ # if self.auth:684+ # if isinstance(self.auth, tuple) and len(self.auth) == 2:685+ # # special-case basic HTTP auth686+ # self.auth = HTTPBasicAuth(*self.auth)687+688+ # # Allow auth to make its changes.689+ # r = self.auth(self)690+691+ # # Update self to reflect the auth changes.692+ # self.__dict__.update(r.__dict__)693+694+ # # Nottin' on you.695+ # body = None696+ # content_type = None697+698+ # # Multi-part file uploads.699+ # if self.files:700+ # (body, content_type) = self._encode_files(self.files)701+ # else:702+ # if self.data:703+704+ # body = self._encode_params(self.data)705+ # if isinstance(self.data, str) or isinstance(self.data, builtin_str) or hasattr(self.data, 'read'):706+ # content_type = None707+ # else:708+ # content_type = 'application/x-www-form-urlencoded'709+710+ # self.headers['Content-Length'] = '0'711+ # if hasattr(body, 'seek') and hasattr(body, 'tell'):712+ # body.seek(0, 2)713+ # self.headers['Content-Length'] = str(body.tell())714+ # body.seek(0, 0)715+ # elif body is not None:716+ # self.headers['Content-Length'] = str(len(body))717+718+ # # Add content-type if it wasn't explicitly provided.719+ # if (content_type) and (not 'content-type' in self.headers):720+ # self.headers['Content-Type'] = content_type721+722+ _p = urlparse(url)723+ no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))724+ proxy = self.proxies.get(_p.scheme)725+726+ if proxy and not any(map(_p.hostname.endswith, no_proxy)):727+ conn = poolmanager.ProxyManager(self.get_connection_for_url(proxy))728+ _proxy = urlparse(proxy)729+ if '@' in _proxy.netloc:730+ auth, url = _proxy.netloc.split('@', 1)731+ self.proxy_auth = HTTPProxyAuth(*auth.split(':', 1))732+ r = self.proxy_auth(self)733+ self.__dict__.update(r.__dict__)734+ else:735+ conn = self.get_connection_for_url(url)736+737+ if not self.config.get('keep_alive'):738+ self.headers['Connection'] = 'close'739+740+ # if url.startswith('https') and self.verify:741+742+ # cert_loc = None743+744+ # # Allow self-specified cert location.745+ # if self.verify is not True:746+ # cert_loc = self.verify747+748+ # # Look for configuration.749+ # if not cert_loc and self.config.get('trust_env'):750+ # cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')751+752+ # # Curl compatibility.753+ # if not cert_loc and self.config.get('trust_env'):754+ # cert_loc = os.environ.get('CURL_CA_BUNDLE')755+756+ # if not cert_loc:757+ # cert_loc = DEFAULT_CA_BUNDLE_PATH758+759+ # if not cert_loc:760+ # raise Exception("Could not find a suitable SSL CA certificate bundle.")761+762+ # conn.cert_reqs = 'CERT_REQUIRED'763+ # conn.ca_certs = cert_loc764+ # else:765+ # conn.cert_reqs = 'CERT_NONE'766+ # conn.ca_certs = None767+768+ # if self.cert:769+ # if len(self.cert) == 2:770+ # conn.cert_file = self.cert[0]771+ # conn.key_file = self.cert[1]772+ # else:773+ # conn.cert_file = self.cert774+775+ if not self.sent or anyway:776+777+ # Skip if 'cookie' header is explicitly set.778+ # if 'cookie' not in self.headers:779+ # cookie_header = get_cookie_header(self.cookies, self)780+ # if cookie_header is not None:781+ # self.headers['Cookie'] = cookie_header782+783+ # Pre-send hook.784+ r = dispatch_hook('pre_send', self.hooks, self)785+ self.__dict__.update(r.__dict__)786+787+ # catch urllib3 exceptions and throw Requests exceptions788+ # try:789+ # # Send the request.790+ # r = conn.urlopen(791+ # method=self.method,792+ # url=self.path_url,793+ # body=body,794+ # headers=self.headers,795+ # redirect=False,796+ # assert_same_host=False,797+ # preload_content=False,798+ # decode_content=False,799+ # retries=self.config.get('max_retries', 0),800+ # timeout=self.timeout,801+ # )802+ # self.sent = True803+804+ # except socket.error as sockerr:805+ # raise ConnectionError(sockerr)806+807+ # except MaxRetryError as e:808+ # raise ConnectionError(e)809+810+ # except (_SSLError, _HTTPError) as e:811+ # if isinstance(e, _SSLError):812+ # raise SSLError(e)813+ # elif isinstance(e, TimeoutError):814+ # raise Timeout(e)815+ # else:816+ # raise Timeout('Request timed out.')817+818+ # build_response can throw TooManyRedirects819+ self._build_response(r)820+821+ # Response manipulation hook.822+ self.response = dispatch_hook('response', self.hooks, self.response)823+824+ # Post-request hook.825+ r = dispatch_hook('post_request', self.hooks, self)826+ self.__dict__.update(r.__dict__)827+828+ # If prefetch is True, mark content as consumed.829+ if prefetch is None:830+ prefetch = self.prefetch831+ if prefetch:832+ # Save the response.833+ self.response.content834+835+ return self.sent836+837+ def get_connection_for_url(self, url):838+ # Check to see if keep_alive is allowed.839+ try:840+ if self.config.get('keep_alive'):841+ conn = self._poolmanager.connection_from_url(url)842+ else:843+ conn = connectionpool.connection_from_url(url)844+ return conn845+ except LocationParseError as e:846+ raise InvalidURL(e)847+848+ def prepare(self):849+ return deepcopy(self)850+851+852 class BaseResponse(object):853 """The basic Respone"""854 def __init__(self):855 self.url = None206 unmodified lines1062 """Returns the parsed header links of the response, if any."""1063 1064 header = self.headers['link']1065 1066+ # l = MultiDict()1067 l = {}1068 1069 if header:1070 links = parse_header_links(header)22 unmodified linesmodified:requests/sessions.py+44 added-26 removed
17 unmodified lines18 from .utils import header_expand, from_key_val_list19 from .packages.urllib3.poolmanager import PoolManager20 21 22+from adapters import HTTPAdapter23+24 def merge_kwargs(local_kwarg, default_kwarg):25 """Merges kwarg dictionaries.26 27 If a local key in the dictionary is set to None, it will be removed.87 unmodified lines115 116 for (k, v) in list(defaults.items()):117 self.config.setdefault(k, deepcopy(v))118 117- self.init_poolmanager()118-119 # Set up a CookieJar to be used by default120 if isinstance(cookies, cookielib.CookieJar):121 self.cookies = cookies122 else:123 self.cookies = cookiejar_from_dict(cookies)124 125- def init_poolmanager(self):126- self.poolmanager = PoolManager(127- num_pools=self.config.get('pool_connections'),128- maxsize=self.config.get('pool_maxsize'),129- strict=not self.config.get('support_http0.9')130- )131-132- def __repr__(self):133- return '<requests-client at 0x%x>' % (id(self))134-125 def __enter__(self):126 return self127 128 def __exit__(self, *args):129 self.close()130 131 def close(self):142- """Dispose of any internal state.132+ pass133 144- Currently, this just closes the PoolManager, which closes pooled145- connections.146- """147- self.poolmanager.clear()148-134 def request(self, method, url,135 params=None,136 data=None,137 headers=None,9 unmodified lines147 prefetch=None,148 verify=None,149 cert=None):150 151+ req = Request()152+ req.method = method153+ req.url = url154+ req.headers = headers155+ req.files = files156+ req.data = data157+ req.params = params158+ req.auth = auth159+ req.cookies = cookies160+ # TODO: move to attached161+ req.allow_redirects = allow_redirects162+ req.proxies = proxies163+ req.hooks = hooks164+165+ prep = req.prepare()166+167+ return self.send(prep)168+169+170+171+172+ def old_request(self, method, url,173+ params=None,174+ data=None,175+ headers=None,176+ cookies=None,177+ files=None,178+ auth=None,179+ timeout=None,180+ allow_redirects=True,181+ proxies=None,182+ hooks=None,183+ return_response=True,184+ config=None,185+ prefetch=None,186+ verify=None,187+ cert=None):188+189 """Constructs and sends a :class:`Request <Request>`.190 Returns :class:`Response <Response>` object.191 192 :param method: method for the new :class:`Request` object.97 unmodified lines290 291 # Send the HTTP Request.292 return self._send_request(r, **args)293 271- def _send_request(self, r, **kwargs):272- # Send the request.273- r.send(prefetch=kwargs.get("prefetch"))274-275- # Return the response.276- return r.response277-294 def get(self, url, **kwargs):295 """Sends a GET request. Returns :class:`Response` object.296 297 :param url: URL for the new :class:`Request` object.63 unmodified lines361 return self.request('delete', url, **kwargs)362 363 def send(self, request):364 """Send a given PreparedRequest."""349- return request.send()365+ adapter = HTTPAdapter()366+ r = adapter.send(request)367+ return r368 369 def __getstate__(self):370 return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)371 11 unmodified lines