Skip to content
Myr

backup

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 5ce4b69 · Browse files · 2 files+482 added−490 removed
This commit

State

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

Diff stats

2 files+482 added−490 removed

  • other:+482 added−490 removed

2 files+482 added−490 removed

modified:requests/models.py+1 added-490 removed
15 unmodified lines
16from datetime import datetime17from io import BytesIO1819from .hooks import dispatch_hook, HOOKS20from .structures import CaseInsensitiveDict20zz21from .status_codes import codes2223from .auth import HTTPBasicAuth, HTTPProxyAuth24from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header
333 unmodified lines
358 cookie_header = get_cookie_header(cookies, self)359 if cookie_header is not None:360 self.headers['Cookie'] = cookie_header361362 def send(self):363 pass364 # return362366 # def prepare_allow_367368369370class OldRequest(object):371 """The :class:`Request <Request>` object. It carries out all functionality372 of Requests. Recommended interface is with the Requests functions.373 """374375 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):395396 #: Dictionary of configurations for this request.397 self.config = dict(config or [])398399 #: Float describes the timeout of the request.400 # (Use socket.setdefaulttimeout() as fallback)401 self.timeout = timeout402403 # URL404405 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.406 self.headers = dict(headers or [])407408 #: Dictionary of files to multipart upload (``{filename: content}``).409 self.files = None410411 #: HTTP Method to use.412 self.method = method413414 #: Dictionary, bytes or file stream of request body data to attach to the415 #: :class:`Request <Request>`.416 self.data = None417418 #: 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 = None422423 #: True if :class:`Request <Request>` is part of a redirect chain (disables history424 #: and HTTPError storage).425 self.redirect = redirect426427 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)428 self.allow_redirects = allow_redirects429430 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})431 self.proxies = dict(proxies or [])432433 for proxy_type, uri_ref in list(self.proxies.items()):434 if not uri_ref:435 del self.proxies[proxy_type]436437 # 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)441442 self.data = data443 self.params = params444 self.files = files445446 #: :class:`Response <Response>` instance, containing447 #: content and metadata of HTTP Response, once :attr:`sent <send>`.448 self.response = Response()449450 #: Authentication tuple or object to attach to :class:`Request <Request>`.451 self.auth = auth452453 # #: 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)458459 #: True if Request has been sent.460 self.sent = False461462 #: Event-handling hooks.463 self.hooks = {}464465 for event in HOOKS:466 self.hooks[event] = []467468 hooks = hooks or {}469470 for (k, v) in list(hooks.items()):471 self.register_hook(event=k, hook=v)472473 #: Session.474 self.session = session475476 #: SSL Verification.477 self.verify = verify478479 #: SSL Certificate480 self.cert = cert481482 #: Prefetch response content483 self.prefetch = prefetch484485 # if headers:486 # headers = CaseInsensitiveDict(self.headers)487 # else:488 # headers = CaseInsensitiveDict()489490 # 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] = v494495 self.headers = headers496 self._poolmanager = _poolmanager497498 def __repr__(self):499 return '<Request [%s]>' % (self.method)500501 def _build_response(self, resp):502 """Build internal :class:`Response <Response>` object503 from given response.504 """505506 def build(resp):507508 response = Response()509510 # Pass settings over.511 response.config = self.config512513 if resp:514515 # Fallback to None if there's no status_code, for whatever reason.516 # response.status_code = getattr(resp, 'status', None)517518 # Make headers case-insensitive.519 # response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))520521 # Set encoding.522 # response.encoding = get_encoding_from_headers(response.headers)523524 # Add new cookies from the server.525 extract_cookies_to_jar(self.cookies, self, resp)526527 # Save cookies in Response.528 response.cookies = self.cookies529530 # Save cookies in Session.531 for cookie in self.cookies:532 self.session.cookies.set_cookie(cookie)533534 # No exceptions were harmed in the making of this request.535 response.error = getattr(resp, 'error', None)536537 # 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_url543544 return response545546 history = []547548 r = build(resp)549 # TODO: session level shit550 if r.status_code in REDIRECT_STATI and not self.redirect:551552 while (('location' in r.headers and r.status_code in REDIRECT_STATI) and553 ((r.status_code is codes.see_other) or (self.allow_redirects))):554555 r.content # Consume socket so it can be released556557 if not len(history) < self.config.get('max_redirects'):558 raise TooManyRedirects()559560 # Release the connection back into the pool.561 r.raw.release_conn()562563 history.append(r)564565 url = r.headers['location']566 data = self.data567 files = self.files568569 # 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)573574 # 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))581582 # 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.method589590 # 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 = None595596 if (r.status_code == 303) and self.method != 'HEAD':597 method = 'GET'598 data = None599 files = None600601 # Remove the cookie headers that were sent.602 headers = self.headers603 try:604 del headers['Cookie']605 except KeyError:606 pass607608 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 )627628 request.send()629 r = request.response630631 r.history = history632633 self.response = r634 self.response.request = self635636637 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))643644 def deregister_hook(self, event, hook):645 """Deregister a previously registered hook.646 Returns True if the hook existed, False if not.647 """648649 try:650 self.hooks[event].remove(hook)651 return True652 except ValueError:653 return False654655 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.659660 Once a request is successfully sent, `sent` will equal True.661662 :param anyway: If True, request will be sent, even if it has663 already been sent.664665 :param prefetch: If not None, will override the request's own setting666 for prefetch.667 """668669 # Build the URL670 url = self.full_url671672 # Pre-request hook.673 r = dispatch_hook('pre_request', self.hooks, self)674 self.__dict__.update(r.__dict__)675676 # Logging677 log.info('Sending %s: %s' % (self, url))678679 # 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)682683 # 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)687688 # # Allow auth to make its changes.689 # r = self.auth(self)690691 # # Update self to reflect the auth changes.692 # self.__dict__.update(r.__dict__)693694 # # Nottin' on you.695 # body = None696 # content_type = None697698 # # Multi-part file uploads.699 # if self.files:700 # (body, content_type) = self._encode_files(self.files)701 # else:702 # if self.data:703704 # 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'709710 # 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))717718 # # 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_type721722 _p = urlparse(url)723 no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))724 proxy = self.proxies.get(_p.scheme)725726 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)736737 if not self.config.get('keep_alive'):738 self.headers['Connection'] = 'close'739740 # if url.startswith('https') and self.verify:741742 # cert_loc = None743744 # # Allow self-specified cert location.745 # if self.verify is not True:746 # cert_loc = self.verify747748 # # Look for configuration.749 # if not cert_loc and self.config.get('trust_env'):750 # cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')751752 # # Curl compatibility.753 # if not cert_loc and self.config.get('trust_env'):754 # cert_loc = os.environ.get('CURL_CA_BUNDLE')755756 # if not cert_loc:757 # cert_loc = DEFAULT_CA_BUNDLE_PATH758759 # if not cert_loc:760 # raise Exception("Could not find a suitable SSL CA certificate bundle.")761762 # conn.cert_reqs = 'CERT_REQUIRED'763 # conn.ca_certs = cert_loc764 # else:765 # conn.cert_reqs = 'CERT_NONE'766 # conn.ca_certs = None767768 # 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.cert774775 if not self.sent or anyway:776777 # 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_header782783 # Pre-send hook.784 r = dispatch_hook('pre_send', self.hooks, self)785 self.__dict__.update(r.__dict__)786787 # 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 = True803804 # except socket.error as sockerr:805 # raise ConnectionError(sockerr)806807 # except MaxRetryError as e:808 # raise ConnectionError(e)809810 # 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.')817818 # build_response can throw TooManyRedirects819 self._build_response(r)820821 # Response manipulation hook.822 self.response = dispatch_hook('response', self.hooks, self.response)823824 # Post-request hook.825 r = dispatch_hook('post_request', self.hooks, self)826 self.__dict__.update(r.__dict__)827828 # 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.content834835 return self.sent836837 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)847848 def prepare(self):849 return deepcopy(self)850851363class BaseResponse(object):364 """The basic Respone"""365 def __init__(self):366 self.url = None
237 unmodified lines
added:backup.py+481 added
12class OldRequest(object):3 """The :class:`Request <Request>` object. It carries out all functionality4 of Requests. Recommended interface is with the Requests functions.5 """67 def __init__(self,8 url=None,9 headers=dict(),10 files=None,11 method=None,12 data=dict(),13 params=dict(),14 auth=None,15 cookies=None,16 timeout=None,17 redirect=False,18 allow_redirects=False,19 proxies=None,20 hooks=None,21 config=None,22 prefetch=True,23 _poolmanager=None,24 verify=None,25 session=None,26 cert=None):2728 #: Dictionary of configurations for this request.29 self.config = dict(config or [])3031 #: Float describes the timeout of the request.32 # (Use socket.setdefaulttimeout() as fallback)33 self.timeout = timeout3435 # URL3637 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.38 self.headers = dict(headers or [])3940 #: Dictionary of files to multipart upload (``{filename: content}``).41 self.files = None4243 #: HTTP Method to use.44 self.method = method4546 #: Dictionary, bytes or file stream of request body data to attach to the47 #: :class:`Request <Request>`.48 self.data = None4950 #: Dictionary of querystring data to attach to the51 #: :class:`Request <Request>`. The dictionary values can be lists for representing52 #: multivalued query parameters.53 self.params = None5455 #: True if :class:`Request <Request>` is part of a redirect chain (disables history56 #: and HTTPError storage).57 self.redirect = redirect5859 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)60 self.allow_redirects = allow_redirects6162 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})63 self.proxies = dict(proxies or [])6465 for proxy_type, uri_ref in list(self.proxies.items()):66 if not uri_ref:67 del self.proxies[proxy_type]6869 # If no proxies are given, allow configuration by environment variables70 # HTTP_PROXY and HTTPS_PROXY.71 if not self.proxies and self.config.get('trust_env'):72 self.proxies = get_environ_proxies(self.url)7374 self.data = data75 self.params = params76 self.files = files7778 #: :class:`Response <Response>` instance, containing79 #: content and metadata of HTTP Response, once :attr:`sent <send>`.80 self.response = Response()8182 #: Authentication tuple or object to attach to :class:`Request <Request>`.83 self.auth = auth8485 # #: CookieJar to attach to :class:`Request <Request>`.86 # if isinstance(cookies, cookielib.CookieJar):87 # self.cookies = cookies88 # else:89 # self.cookies = cookiejar_from_dict(cookies)9091 #: True if Request has been sent.92 self.sent = False9394 #: Event-handling hooks.95 self.hooks = {}9697 for event in HOOKS:98 self.hooks[event] = []99100 hooks = hooks or {}101102 for (k, v) in list(hooks.items()):103 self.register_hook(event=k, hook=v)104105 #: Session.106 self.session = session107108 #: SSL Verification.109 self.verify = verify110111 #: SSL Certificate112 self.cert = cert113114 #: Prefetch response content115 self.prefetch = prefetch116117 # if headers:118 # headers = CaseInsensitiveDict(self.headers)119 # else:120 # headers = CaseInsensitiveDict()121122 # Add configured base headers.123 for (k, v) in list(self.config.get('base_headers', {}).items()):124 if k not in headers:125 headers[k] = v126127 self.headers = headers128 self._poolmanager = _poolmanager129130 def __repr__(self):131 return '<Request [%s]>' % (self.method)132133 def _build_response(self, resp):134 """Build internal :class:`Response <Response>` object135 from given response.136 """137138 def build(resp):139140 response = Response()141142 # Pass settings over.143 response.config = self.config144145 if resp:146147 # Fallback to None if there's no status_code, for whatever reason.148 # response.status_code = getattr(resp, 'status', None)149150 # Make headers case-insensitive.151 # response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))152153 # Set encoding.154 # response.encoding = get_encoding_from_headers(response.headers)155156 # Add new cookies from the server.157 extract_cookies_to_jar(self.cookies, self, resp)158159 # Save cookies in Response.160 response.cookies = self.cookies161162 # Save cookies in Session.163 for cookie in self.cookies:164 self.session.cookies.set_cookie(cookie)165166 # No exceptions were harmed in the making of this request.167 response.error = getattr(resp, 'error', None)168169 # Save original response for later.170 response.raw = resp171 if isinstance(self.full_url, bytes):172 response.url = self.full_url.decode('utf-8')173 else:174 response.url = self.full_url175176 return response177178 history = []179180 r = build(resp)181 # TODO: session level shit182 if r.status_code in REDIRECT_STATI and not self.redirect:183184 while (('location' in r.headers and r.status_code in REDIRECT_STATI) and185 ((r.status_code is codes.see_other) or (self.allow_redirects))):186187 r.content # Consume socket so it can be released188189 if not len(history) < self.config.get('max_redirects'):190 raise TooManyRedirects()191192 # Release the connection back into the pool.193 r.raw.release_conn()194195 history.append(r)196197 url = r.headers['location']198 data = self.data199 files = self.files200201 # Handle redirection without scheme (see: RFC 1808 Section 4)202 if url.startswith('//'):203 parsed_rurl = urlparse(r.url)204 url = '%s:%s' % (parsed_rurl.scheme, url)205206 # Facilitate non-RFC2616-compliant 'location' headers207 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')208 if not urlparse(url).netloc:209 url = urljoin(r.url,210 # Compliant with RFC3986, we percent211 # encode the url.212 requote_uri(url))213214 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4215 if r.status_code is codes.see_other:216 method = 'GET'217 data = None218 files = None219 else:220 method = self.method221222 # Do what the browsers do, despite standards...223 if r.status_code in (codes.moved, codes.found) and self.method == 'POST':224 method = 'GET'225 data = None226 files = None227228 if (r.status_code == 303) and self.method != 'HEAD':229 method = 'GET'230 data = None231 files = None232233 # Remove the cookie headers that were sent.234 headers = self.headers235 try:236 del headers['Cookie']237 except KeyError:238 pass239240 request = Request(241 url=url,242 headers=headers,243 files=files,244 method=method,245 params=self.session.params,246 auth=self.auth,247 cookies=self.cookies,248 redirect=True,249 data=data,250 config=self.config,251 timeout=self.timeout,252 _poolmanager=self._poolmanager,253 proxies=self.proxies,254 verify=self.verify,255 session=self.session,256 cert=self.cert,257 prefetch=self.prefetch258 )259260 request.send()261 r = request.response262263 r.history = history264265 self.response = r266 self.response.request = self267268269 def register_hook(self, event, hook):270 """Properly register a hook."""271 if isinstance(hook, collections.Callable):272 self.hooks[event].append(hook)273 elif hasattr(hook, '__iter__'):274 self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))275276 def deregister_hook(self, event, hook):277 """Deregister a previously registered hook.278 Returns True if the hook existed, False if not.279 """280281 try:282 self.hooks[event].remove(hook)283 return True284 except ValueError:285 return False286287 def send(self, anyway=False, prefetch=None):288 """Sends the request. Returns True if successful, False if not.289 If there was an HTTPError during transmission,290 self.response.status_code will contain the HTTPError code.291292 Once a request is successfully sent, `sent` will equal True.293294 :param anyway: If True, request will be sent, even if it has295 already been sent.296297 :param prefetch: If not None, will override the request's own setting298 for prefetch.299 """300301 # Build the URL302 url = self.full_url303304 # Pre-request hook.305 r = dispatch_hook('pre_request', self.hooks, self)306 self.__dict__.update(r.__dict__)307308 # Logging309 log.info('Sending %s: %s' % (self, url))310311 # Use .netrc auth if none was provided.312 if not self.auth and self.config.get('trust_env'):313 self.auth = get_netrc_auth(url)314315 # if self.auth:316 # if isinstance(self.auth, tuple) and len(self.auth) == 2:317 # # special-case basic HTTP auth318 # self.auth = HTTPBasicAuth(*self.auth)319320 # # Allow auth to make its changes.321 # r = self.auth(self)322323 # # Update self to reflect the auth changes.324 # self.__dict__.update(r.__dict__)325326 # # Nottin' on you.327 # body = None328 # content_type = None329330 # # Multi-part file uploads.331 # if self.files:332 # (body, content_type) = self._encode_files(self.files)333 # else:334 # if self.data:335336 # body = self._encode_params(self.data)337 # if isinstance(self.data, str) or isinstance(self.data, builtin_str) or hasattr(self.data, 'read'):338 # content_type = None339 # else:340 # content_type = 'application/x-www-form-urlencoded'341342 # self.headers['Content-Length'] = '0'343 # if hasattr(body, 'seek') and hasattr(body, 'tell'):344 # body.seek(0, 2)345 # self.headers['Content-Length'] = str(body.tell())346 # body.seek(0, 0)347 # elif body is not None:348 # self.headers['Content-Length'] = str(len(body))349350 # # Add content-type if it wasn't explicitly provided.351 # if (content_type) and (not 'content-type' in self.headers):352 # self.headers['Content-Type'] = content_type353354 _p = urlparse(url)355 no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))356 proxy = self.proxies.get(_p.scheme)357358 if proxy and not any(map(_p.hostname.endswith, no_proxy)):359 conn = poolmanager.ProxyManager(self.get_connection_for_url(proxy))360 _proxy = urlparse(proxy)361 if '@' in _proxy.netloc:362 auth, url = _proxy.netloc.split('@', 1)363 self.proxy_auth = HTTPProxyAuth(*auth.split(':', 1))364 r = self.proxy_auth(self)365 self.__dict__.update(r.__dict__)366 else:367 conn = self.get_connection_for_url(url)368369 if not self.config.get('keep_alive'):370 self.headers['Connection'] = 'close'371372 # if url.startswith('https') and self.verify:373374 # cert_loc = None375376 # # Allow self-specified cert location.377 # if self.verify is not True:378 # cert_loc = self.verify379380 # # Look for configuration.381 # if not cert_loc and self.config.get('trust_env'):382 # cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')383384 # # Curl compatibility.385 # if not cert_loc and self.config.get('trust_env'):386 # cert_loc = os.environ.get('CURL_CA_BUNDLE')387388 # if not cert_loc:389 # cert_loc = DEFAULT_CA_BUNDLE_PATH390391 # if not cert_loc:392 # raise Exception("Could not find a suitable SSL CA certificate bundle.")393394 # conn.cert_reqs = 'CERT_REQUIRED'395 # conn.ca_certs = cert_loc396 # else:397 # conn.cert_reqs = 'CERT_NONE'398 # conn.ca_certs = None399400 # if self.cert:401 # if len(self.cert) == 2:402 # conn.cert_file = self.cert[0]403 # conn.key_file = self.cert[1]404 # else:405 # conn.cert_file = self.cert406407 if not self.sent or anyway:408409 # Skip if 'cookie' header is explicitly set.410 # if 'cookie' not in self.headers:411 # cookie_header = get_cookie_header(self.cookies, self)412 # if cookie_header is not None:413 # self.headers['Cookie'] = cookie_header414415 # Pre-send hook.416 r = dispatch_hook('pre_send', self.hooks, self)417 self.__dict__.update(r.__dict__)418419 # catch urllib3 exceptions and throw Requests exceptions420 # try:421 # # Send the request.422 # r = conn.urlopen(423 # method=self.method,424 # url=self.path_url,425 # body=body,426 # headers=self.headers,427 # redirect=False,428 # assert_same_host=False,429 # preload_content=False,430 # decode_content=False,431 # retries=self.config.get('max_retries', 0),432 # timeout=self.timeout,433 # )434 # self.sent = True435436 # except socket.error as sockerr:437 # raise ConnectionError(sockerr)438439 # except MaxRetryError as e:440 # raise ConnectionError(e)441442 # except (_SSLError, _HTTPError) as e:443 # if isinstance(e, _SSLError):444 # raise SSLError(e)445 # elif isinstance(e, TimeoutError):446 # raise Timeout(e)447 # else:448 # raise Timeout('Request timed out.')449450 # build_response can throw TooManyRedirects451 self._build_response(r)452453 # Response manipulation hook.454 self.response = dispatch_hook('response', self.hooks, self.response)455456 # Post-request hook.457 r = dispatch_hook('post_request', self.hooks, self)458 self.__dict__.update(r.__dict__)459460 # If prefetch is True, mark content as consumed.461 if prefetch is None:462 prefetch = self.prefetch463 if prefetch:464 # Save the response.465 self.response.content466467 return self.sent468469 def get_connection_for_url(self, url):470 # Check to see if keep_alive is allowed.471 try:472 if self.config.get('keep_alive'):473 conn = self._poolmanager.connection_from_url(url)474 else:475 conn = connectionpool.connection_from_url(url)476 return conn477 except LocationParseError as e:478 raise InvalidURL(e)479480 def prepare(self):481 return deepcopy(self)