Skip to content
Myr

cleanup

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 42a206e · Browse files · 4 files+127 added−623 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+127 added−623 removed

  • other:+127 added−623 removed

4 files+127 added−623 removed

modified:requests/cookies.py+2 added-2 removed
36 unmodified lines
37 def get_type(self):38 return self.type3940 def get_host(self):41 return urlparse(self._r.full_url).netloc41 return urlparse(self._r.url).netloc4243 def get_origin_req_host(self):44 if self._r.response.history:45 r = self._r.response.history[0]
1 unmodified line
47 else:48 return self.get_host()4950 def get_full_url(self):51 return self._r.full_url51 return self._r.url5253 def is_unverifiable(self):54 # unverifiable == redirected55 return bool(self._r.response.history)
323 unmodified lines
modified:requests/models.py+2 added-497 removed
9 unmodified lines
10import os11import socket12import collections13import logging14from copy import deepcopy1415from datetime import datetime16from io import BytesIO17
299 unmodified lines
317 self.headers['Content-Type'] = content_type318319 self.body = body320322323321 def prepare_auth(self, auth):322 """Prepares the given HTTP auth data."""323 if auth:324 if isinstance(auth, tuple) and len(auth) == 2:325 # special-case basic HTTP auth326 auth = HTTPBasicAuth(*auth)
4 unmodified lines
331 # Update self to reflect the auth changes.332 self.__dict__.update(r.__dict__)333334 def prepare_cookies(self, cookies):335 """Prepares the given HTTP cookie data."""336337 if isinstance(cookies, cookielib.CookieJar):338 cookies = cookies339 else:
4 unmodified lines
344 if cookie_header is not None:345 self.headers['Cookie'] = cookie_header346347349350class OldRequest(object):351 """The :class:`Request <Request>` object. It carries out all functionality352 of Requests. Recommended interface is with the Requests functions.353 """354355 def __init__(self,356 url=None,357 headers=dict(),358 files=None,359 method=None,360 data=dict(),361 params=dict(),362 auth=None,363 cookies=None,364 timeout=None,365 redirect=False,366 allow_redirects=False,367 proxies=None,368 hooks=None,369 config=None,370 prefetch=True,371 _poolmanager=None,372 verify=None,373 session=None,374 cert=None):375376 #: Dictionary of configurations for this request.377 self.config = dict(config or [])378379 #: Float describes the timeout of the request.380 # (Use socket.setdefaulttimeout() as fallback)381 self.timeout = timeout382383 # URL384385 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.386 self.headers = dict(headers or [])387388 #: Dictionary of files to multipart upload (``{filename: content}``).389 self.files = None390391 #: HTTP Method to use.392 self.method = method393394 #: Dictionary, bytes or file stream of request body data to attach to the395 #: :class:`Request <Request>`.396 self.data = None397398 #: Dictionary of querystring data to attach to the399 #: :class:`Request <Request>`. The dictionary values can be lists for representing400 #: multivalued query parameters.401 self.params = None402403 #: True if :class:`Request <Request>` is part of a redirect chain (disables history404 #: and HTTPError storage).405 self.redirect = redirect406407 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)408 self.allow_redirects = allow_redirects409410 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})411 self.proxies = dict(proxies or [])412413 for proxy_type, uri_ref in list(self.proxies.items()):414 if not uri_ref:415 del self.proxies[proxy_type]416417 # If no proxies are given, allow configuration by environment variables418 # HTTP_PROXY and HTTPS_PROXY.419 if not self.proxies and self.config.get('trust_env'):420 self.proxies = get_environ_proxies(self.url)421422 self.data = data423 self.params = params424 self.files = files425426 #: :class:`Response <Response>` instance, containing427 #: content and metadata of HTTP Response, once :attr:`sent <send>`.428 self.response = Response()429430 #: Authentication tuple or object to attach to :class:`Request <Request>`.431 self.auth = auth432433 # #: CookieJar to attach to :class:`Request <Request>`.434 # if isinstance(cookies, cookielib.CookieJar):435 # self.cookies = cookies436 # else:437 # self.cookies = cookiejar_from_dict(cookies)438439 #: True if Request has been sent.440 self.sent = False441442 #: Event-handling hooks.443 self.hooks = {}444445 for event in HOOKS:446 self.hooks[event] = []447448 hooks = hooks or {}449450 for (k, v) in list(hooks.items()):451 self.register_hook(event=k, hook=v)452453 #: Session.454 self.session = session455456 #: SSL Verification.457 self.verify = verify458459 #: SSL Certificate460 self.cert = cert461462 #: Prefetch response content463 self.prefetch = prefetch464465 # if headers:466 # headers = CaseInsensitiveDict(self.headers)467 # else:468 # headers = CaseInsensitiveDict()469470 # Add configured base headers.471 for (k, v) in list(self.config.get('base_headers', {}).items()):472 if k not in headers:473 headers[k] = v474475 self.headers = headers476 self._poolmanager = _poolmanager477478 def __repr__(self):479 return '<Request [%s]>' % (self.method)480481 def _build_response(self, resp):482 """Build internal :class:`Response <Response>` object483 from given response.484 """485486 def build(resp):487488 response = Response()489490 # Pass settings over.491 response.config = self.config492493 if resp:494495 # Fallback to None if there's no status_code, for whatever reason.496 # response.status_code = getattr(resp, 'status', None)497498 # Make headers case-insensitive.499 # response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))500501 # Set encoding.502 # response.encoding = get_encoding_from_headers(response.headers)503504 # Add new cookies from the server.505 extract_cookies_to_jar(self.cookies, self, resp)506507 # Save cookies in Response.508 response.cookies = self.cookies509510 # Save cookies in Session.511 for cookie in self.cookies:512 self.session.cookies.set_cookie(cookie)513514 # No exceptions were harmed in the making of this request.515 response.error = getattr(resp, 'error', None)516517 # Save original response for later.518 response.raw = resp519 if isinstance(self.full_url, bytes):520 response.url = self.full_url.decode('utf-8')521 else:522 response.url = self.full_url523524 return response525526 history = []527528 r = build(resp)529 # TODO: session level shit530 if r.status_code in REDIRECT_STATI and not self.redirect:531532 while (('location' in r.headers and r.status_code in REDIRECT_STATI) and533 ((r.status_code is codes.see_other) or (self.allow_redirects))):534535 r.content # Consume socket so it can be released536537 if not len(history) < self.config.get('max_redirects'):538 raise TooManyRedirects()539540 # Release the connection back into the pool.541 r.raw.release_conn()542543 history.append(r)544545 url = r.headers['location']546 data = self.data547 files = self.files548549 # Handle redirection without scheme (see: RFC 1808 Section 4)550 if url.startswith('//'):551 parsed_rurl = urlparse(r.url)552 url = '%s:%s' % (parsed_rurl.scheme, url)553554 # Facilitate non-RFC2616-compliant 'location' headers555 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')556 if not urlparse(url).netloc:557 url = urljoin(r.url,558 # Compliant with RFC3986, we percent559 # encode the url.560 requote_uri(url))561562 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4563 if r.status_code is codes.see_other:564 method = 'GET'565 data = None566 files = None567 else:568 method = self.method569570 # Do what the browsers do, despite standards...571 if r.status_code in (codes.moved, codes.found) and self.method == 'POST':572 method = 'GET'573 data = None574 files = None575576 if (r.status_code == 303) and self.method != 'HEAD':577 method = 'GET'578 data = None579 files = None580581 # Remove the cookie headers that were sent.582 headers = self.headers583 try:584 del headers['Cookie']585 except KeyError:586 pass587588 request = Request(589 url=url,590 headers=headers,591 files=files,592 method=method,593 params=self.session.params,594 auth=self.auth,595 cookies=self.cookies,596 redirect=True,597 data=data,598 config=self.config,599 timeout=self.timeout,600 _poolmanager=self._poolmanager,601 proxies=self.proxies,602 verify=self.verify,603 session=self.session,604 cert=self.cert,605 prefetch=self.prefetch606 )607608 request.send()609 r = request.response610611 r.history = history612613 self.response = r614 self.response.request = self615616617 def register_hook(self, event, hook):618 """Properly register a hook."""619 if isinstance(hook, collections.Callable):620 self.hooks[event].append(hook)621 elif hasattr(hook, '__iter__'):622 self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))623624 def deregister_hook(self, event, hook):625 """Deregister a previously registered hook.626 Returns True if the hook existed, False if not.627 """628629 try:630 self.hooks[event].remove(hook)631 return True632 except ValueError:633 return False634635 def send(self, anyway=False, prefetch=None):636 """Sends the request. Returns True if successful, False if not.637 If there was an HTTPError during transmission,638 self.response.status_code will contain the HTTPError code.639640 Once a request is successfully sent, `sent` will equal True.641642 :param anyway: If True, request will be sent, even if it has643 already been sent.644645 :param prefetch: If not None, will override the request's own setting646 for prefetch.647 """648649 # Build the URL650 url = self.full_url651652 # Pre-request hook.653 r = dispatch_hook('pre_request', self.hooks, self)654 self.__dict__.update(r.__dict__)655656 # Logging657 log.info('Sending %s: %s' % (self, url))658659 # Use .netrc auth if none was provided.660 if not self.auth and self.config.get('trust_env'):661 self.auth = get_netrc_auth(url)662663 # if self.auth:664 # if isinstance(self.auth, tuple) and len(self.auth) == 2:665 # # special-case basic HTTP auth666 # self.auth = HTTPBasicAuth(*self.auth)667668 # # Allow auth to make its changes.669 # r = self.auth(self)670671 # # Update self to reflect the auth changes.672 # self.__dict__.update(r.__dict__)673674 # # Nottin' on you.675 # body = None676 # content_type = None677678 # # Multi-part file uploads.679 # if self.files:680 # (body, content_type) = self._encode_files(self.files)681 # else:682 # if self.data:683684 # body = self._encode_params(self.data)685 # if isinstance(self.data, str) or isinstance(self.data, builtin_str) or hasattr(self.data, 'read'):686 # content_type = None687 # else:688 # content_type = 'application/x-www-form-urlencoded'689690 # self.headers['Content-Length'] = '0'691 # if hasattr(body, 'seek') and hasattr(body, 'tell'):692 # body.seek(0, 2)693 # self.headers['Content-Length'] = str(body.tell())694 # body.seek(0, 0)695 # elif body is not None:696 # self.headers['Content-Length'] = str(len(body))697698 # # Add content-type if it wasn't explicitly provided.699 # if (content_type) and (not 'content-type' in self.headers):700 # self.headers['Content-Type'] = content_type701702 _p = urlparse(url)703 no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))704 proxy = self.proxies.get(_p.scheme)705706 if proxy and not any(map(_p.hostname.endswith, no_proxy)):707 conn = poolmanager.ProxyManager(self.get_connection_for_url(proxy))708 _proxy = urlparse(proxy)709 if '@' in _proxy.netloc:710 auth, url = _proxy.netloc.split('@', 1)711 self.proxy_auth = HTTPProxyAuth(*auth.split(':', 1))712 r = self.proxy_auth(self)713 self.__dict__.update(r.__dict__)714 else:715 conn = self.get_connection_for_url(url)716717 if not self.config.get('keep_alive'):718 self.headers['Connection'] = 'close'719720 # if url.startswith('https') and self.verify:721722 # cert_loc = None723724 # # Allow self-specified cert location.725 # if self.verify is not True:726 # cert_loc = self.verify727728 # # Look for configuration.729 # if not cert_loc and self.config.get('trust_env'):730 # cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')731732 # # Curl compatibility.733 # if not cert_loc and self.config.get('trust_env'):734 # cert_loc = os.environ.get('CURL_CA_BUNDLE')735736 # if not cert_loc:737 # cert_loc = DEFAULT_CA_BUNDLE_PATH738739 # if not cert_loc:740 # raise Exception("Could not find a suitable SSL CA certificate bundle.")741742 # conn.cert_reqs = 'CERT_REQUIRED'743 # conn.ca_certs = cert_loc744 # else:745 # conn.cert_reqs = 'CERT_NONE'746 # conn.ca_certs = None747748 # if self.cert:749 # if len(self.cert) == 2:750 # conn.cert_file = self.cert[0]751 # conn.key_file = self.cert[1]752 # else:753 # conn.cert_file = self.cert754755 if not self.sent or anyway:756757 # Skip if 'cookie' header is explicitly set.758 # if 'cookie' not in self.headers:759 # cookie_header = get_cookie_header(self.cookies, self)760 # if cookie_header is not None:761 # self.headers['Cookie'] = cookie_header762763 # Pre-send hook.764 r = dispatch_hook('pre_send', self.hooks, self)765 self.__dict__.update(r.__dict__)766767 # catch urllib3 exceptions and throw Requests exceptions768 # try:769 # # Send the request.770 # r = conn.urlopen(771 # method=self.method,772 # url=self.path_url,773 # body=body,774 # headers=self.headers,775 # redirect=False,776 # assert_same_host=False,777 # preload_content=False,778 # decode_content=False,779 # retries=self.config.get('max_retries', 0),780 # timeout=self.timeout,781 # )782 # self.sent = True783784 # except socket.error as sockerr:785 # raise ConnectionError(sockerr)786787 # except MaxRetryError as e:788 # raise ConnectionError(e)789790 # except (_SSLError, _HTTPError) as e:791 # if isinstance(e, _SSLError):792 # raise SSLError(e)793 # elif isinstance(e, TimeoutError):794 # raise Timeout(e)795 # else:796 # raise Timeout('Request timed out.')797798 # build_response can throw TooManyRedirects799 self._build_response(r)800801 # Response manipulation hook.802 self.response = dispatch_hook('response', self.hooks, self.response)803804 # Post-request hook.805 r = dispatch_hook('post_request', self.hooks, self)806 self.__dict__.update(r.__dict__)807808 # If prefetch is True, mark content as consumed.809 if prefetch is None:810 prefetch = self.prefetch811 if prefetch:812 # Save the response.813 self.response.content814815 return self.sent816817 def get_connection_for_url(self, url):818 # Check to see if keep_alive is allowed.819 try:820 if self.config.get('keep_alive'):821 conn = self._poolmanager.connection_from_url(url)822 else:823 conn = connectionpool.connection_from_url(url)824 return conn825 except LocationParseError as e:826 raise InvalidURL(e)827828 def prepare(self):829 return deepcopy(self)830831832# class BaseResponse(object):833# """The basic Respone"""834# def __init__(self):835# self.url = None836# self.status_code = None837# self.reason = None838# self.headers = None839# self.data = None840# self.body = None841842348class Response(object):349 """The core :class:`Response <Response>` object. All350 :class:`Request <Request>` objects contain a351 :class:`response <Response>` attribute, which is an instance
226 unmodified lines
modified:requests/sessions.py-124 removed
167 unmodified lines
168169 return self.send(prep)170171172173174 def old_request(self, method, url,175 params=None,176 data=None,177 headers=None,178 cookies=None,179 files=None,180 auth=None,181 timeout=None,182 allow_redirects=True,183 proxies=None,184 hooks=None,185 return_response=True,186 config=None,187 prefetch=None,188 verify=None,189 cert=None):190191 """Constructs and sends a :class:`Request <Request>`.192 Returns :class:`Response <Response>` object.193194 :param method: method for the new :class:`Request` object.195 :param url: URL for the new :class:`Request` object.196 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.197 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.198 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.199 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.200 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.201 :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.202 :param timeout: (optional) Float describing the timeout of the request.203 :param allow_redirects: (optional) Boolean. Set to True by default.204 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.205 :param return_response: (optional) If False, an un-sent Request object will returned.206 :param config: (optional) A configuration dictionary. See ``request.defaults`` for allowed keys and their default values.207 :param prefetch: (optional) whether to immediately download the response content. Defaults to ``True``.208 :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.209 :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.210 """211212 method = str(method).upper()213214 # Default empty dicts for dict params.215 data = [] if data is None else data216 files = [] if files is None else files217 headers = {} if headers is None else headers218 params = {} if params is None else params219 hooks = {} if hooks is None else hooks220 prefetch = prefetch if prefetch is not None else self.prefetch221222 # use session's hooks as defaults223 for key, cb in list(self.hooks.items()):224 hooks.setdefault(key, cb)225226 # Expand header values.227 if headers:228 for k, v in list(headers.items() or {}):229 headers[k] = header_expand(v)230231 args = dict(232 method=method,233 url=url,234 data=data,235 params=from_key_val_list(params),236 headers=from_key_val_list(headers),237 cookies=cookies,238 files=files,239 auth=auth,240 hooks=from_key_val_list(hooks),241 timeout=timeout,242 allow_redirects=allow_redirects,243 proxies=from_key_val_list(proxies),244 config=from_key_val_list(config),245 prefetch=prefetch,246 verify=verify,247 cert=cert,248 _poolmanager=self.poolmanager249 )250251 # merge session cookies into passed-in ones252 dead_cookies = None253 # passed-in cookies must become a CookieJar:254 if not isinstance(cookies, cookielib.CookieJar):255 args['cookies'] = cookiejar_from_dict(cookies)256 # support unsetting cookies that have been passed in with None values257 # this is only meaningful when `cookies` is a dict ---258 # for a real CookieJar, the client should use session.cookies.clear()259 if cookies is not None:260 dead_cookies = [name for name in cookies if cookies[name] is None]261 # merge the session's cookies into the passed-in cookies:262 for cookie in self.cookies:263 args['cookies'].set_cookie(cookie)264 # remove the unset cookies from the jar we'll be using with the current request265 # (but not from the session's own store of cookies):266 if dead_cookies is not None:267 for name in dead_cookies:268 remove_cookie_by_name(args['cookies'], name)269270 # Merge local kwargs with session kwargs.271 for attr in self.__attrs__:272 # we already merged cookies:273 if attr == 'cookies':274 continue275276 session_val = getattr(self, attr, None)277 local_val = args.get(attr)278 args[attr] = merge_kwargs(local_val, session_val)279280 # Arguments manipulation hook.281 args = dispatch_hook('args', args['hooks'], args)282283 # Create the (empty) response.284 r = Request(**args)285286 # Give the response some context.287 r.session = self288289 # Don't send if asked nicely.290 if not return_response:291 return r292293 # Send the HTTP Request.294 return self._send_request(r, **args)295172 def get(self, url, **kwargs):173 """Sends a GET request. Returns :class:`Response` object.174175 :param url: URL for the new :class:`Request` object.
85 unmodified lines
modified:backup.py+123 added
12 def old_request(self, method, url,3 params=None,4 data=None,5 headers=None,6 cookies=None,7 files=None,8 auth=None,9 timeout=None,10 allow_redirects=True,11 proxies=None,12 hooks=None,13 return_response=True,14 config=None,15 prefetch=None,16 verify=None,17 cert=None):1819 """Constructs and sends a :class:`Request <Request>`.20 Returns :class:`Response <Response>` object.2122 :param method: method for the new :class:`Request` object.23 :param url: URL for the new :class:`Request` object.24 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.25 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.26 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.27 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.28 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.29 :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.30 :param timeout: (optional) Float describing the timeout of the request.31 :param allow_redirects: (optional) Boolean. Set to True by default.32 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.33 :param return_response: (optional) If False, an un-sent Request object will returned.34 :param config: (optional) A configuration dictionary. See ``request.defaults`` for allowed keys and their default values.35 :param prefetch: (optional) whether to immediately download the response content. Defaults to ``True``.36 :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.37 :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.38 """3940 method = str(method).upper()4142 # Default empty dicts for dict params.43 data = [] if data is None else data44 files = [] if files is None else files45 headers = {} if headers is None else headers46 params = {} if params is None else params47 hooks = {} if hooks is None else hooks48 prefetch = prefetch if prefetch is not None else self.prefetch4950 # use session's hooks as defaults51 for key, cb in list(self.hooks.items()):52 hooks.setdefault(key, cb)5354 # Expand header values.55 if headers:56 for k, v in list(headers.items() or {}):57 headers[k] = header_expand(v)5859 args = dict(60 method=method,61 url=url,62 data=data,63 params=from_key_val_list(params),64 headers=from_key_val_list(headers),65 cookies=cookies,66 files=files,67 auth=auth,68 hooks=from_key_val_list(hooks),69 timeout=timeout,70 allow_redirects=allow_redirects,71 proxies=from_key_val_list(proxies),72 config=from_key_val_list(config),73 prefetch=prefetch,74 verify=verify,75 cert=cert,76 _poolmanager=self.poolmanager77 )7879 # merge session cookies into passed-in ones80 dead_cookies = None81 # passed-in cookies must become a CookieJar:82 if not isinstance(cookies, cookielib.CookieJar):83 args['cookies'] = cookiejar_from_dict(cookies)84 # support unsetting cookies that have been passed in with None values85 # this is only meaningful when `cookies` is a dict ---86 # for a real CookieJar, the client should use session.cookies.clear()87 if cookies is not None:88 dead_cookies = [name for name in cookies if cookies[name] is None]89 # merge the session's cookies into the passed-in cookies:90 for cookie in self.cookies:91 args['cookies'].set_cookie(cookie)92 # remove the unset cookies from the jar we'll be using with the current request93 # (but not from the session's own store of cookies):94 if dead_cookies is not None:95 for name in dead_cookies:96 remove_cookie_by_name(args['cookies'], name)9798 # Merge local kwargs with session kwargs.99 for attr in self.__attrs__:100 # we already merged cookies:101 if attr == 'cookies':102 continue103104 session_val = getattr(self, attr, None)105 local_val = args.get(attr)106 args[attr] = merge_kwargs(local_val, session_val)107108 # Arguments manipulation hook.109 args = dispatch_hook('args', args['hooks'], args)110111 # Create the (empty) response.112 r = Request(**args)113114 # Give the response some context.115 r.session = self116117 # Don't send if asked nicely.118 if not return_response:119 return r120121 # Send the HTTP Request.122 return self._send_request(r, **args)123124125class OldRequest(object):126 """The :class:`Request <Request>` object. It carries out all functionality127 of Requests. Recommended interface is with the Requests functions.128 """
476 unmodified lines