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
Provenance
- Commit
3aefb8e- Tree
f3bdc16- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
5ce4b69
2 files changed+482 added−490 removed
modified:requests/models.py+1 added-490 removed
15 unmodified lines16 from datetime import datetime17 from io import BytesIO18 19 from .hooks import dispatch_hook, HOOKS20-from .structures import CaseInsensitiveDict20+zz21 from .status_codes import codes22 23 from .auth import HTTPBasicAuth, HTTPProxyAuth24 from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header333 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- # return362 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-363 class BaseResponse(object):364 """The basic Respone"""365 def __init__(self):366 self.url = None237 unmodified linesadded:backup.py+481 added
1+2+class OldRequest(object):3+ """The :class:`Request <Request>` object. It carries out all functionality4+ of Requests. Recommended interface is with the Requests functions.5+ """6+7+ 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):27+28+ #: Dictionary of configurations for this request.29+ self.config = dict(config or [])30+31+ #: Float describes the timeout of the request.32+ # (Use socket.setdefaulttimeout() as fallback)33+ self.timeout = timeout34+35+ # URL36+37+ #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.38+ self.headers = dict(headers or [])39+40+ #: Dictionary of files to multipart upload (``{filename: content}``).41+ self.files = None42+43+ #: HTTP Method to use.44+ self.method = method45+46+ #: Dictionary, bytes or file stream of request body data to attach to the47+ #: :class:`Request <Request>`.48+ self.data = None49+50+ #: 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 = None54+55+ #: True if :class:`Request <Request>` is part of a redirect chain (disables history56+ #: and HTTPError storage).57+ self.redirect = redirect58+59+ #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)60+ self.allow_redirects = allow_redirects61+62+ # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})63+ self.proxies = dict(proxies or [])64+65+ for proxy_type, uri_ref in list(self.proxies.items()):66+ if not uri_ref:67+ del self.proxies[proxy_type]68+69+ # 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)73+74+ self.data = data75+ self.params = params76+ self.files = files77+78+ #: :class:`Response <Response>` instance, containing79+ #: content and metadata of HTTP Response, once :attr:`sent <send>`.80+ self.response = Response()81+82+ #: Authentication tuple or object to attach to :class:`Request <Request>`.83+ self.auth = auth84+85+ # #: 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)90+91+ #: True if Request has been sent.92+ self.sent = False93+94+ #: Event-handling hooks.95+ self.hooks = {}96+97+ for event in HOOKS:98+ self.hooks[event] = []99+100+ hooks = hooks or {}101+102+ for (k, v) in list(hooks.items()):103+ self.register_hook(event=k, hook=v)104+105+ #: Session.106+ self.session = session107+108+ #: SSL Verification.109+ self.verify = verify110+111+ #: SSL Certificate112+ self.cert = cert113+114+ #: Prefetch response content115+ self.prefetch = prefetch116+117+ # if headers:118+ # headers = CaseInsensitiveDict(self.headers)119+ # else:120+ # headers = CaseInsensitiveDict()121+122+ # 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] = v126+127+ self.headers = headers128+ self._poolmanager = _poolmanager129+130+ def __repr__(self):131+ return '<Request [%s]>' % (self.method)132+133+ def _build_response(self, resp):134+ """Build internal :class:`Response <Response>` object135+ from given response.136+ """137+138+ def build(resp):139+140+ response = Response()141+142+ # Pass settings over.143+ response.config = self.config144+145+ if resp:146+147+ # Fallback to None if there's no status_code, for whatever reason.148+ # response.status_code = getattr(resp, 'status', None)149+150+ # Make headers case-insensitive.151+ # response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))152+153+ # Set encoding.154+ # response.encoding = get_encoding_from_headers(response.headers)155+156+ # Add new cookies from the server.157+ extract_cookies_to_jar(self.cookies, self, resp)158+159+ # Save cookies in Response.160+ response.cookies = self.cookies161+162+ # Save cookies in Session.163+ for cookie in self.cookies:164+ self.session.cookies.set_cookie(cookie)165+166+ # No exceptions were harmed in the making of this request.167+ response.error = getattr(resp, 'error', None)168+169+ # 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_url175+176+ return response177+178+ history = []179+180+ r = build(resp)181+ # TODO: session level shit182+ if r.status_code in REDIRECT_STATI and not self.redirect:183+184+ while (('location' in r.headers and r.status_code in REDIRECT_STATI) and185+ ((r.status_code is codes.see_other) or (self.allow_redirects))):186+187+ r.content # Consume socket so it can be released188+189+ if not len(history) < self.config.get('max_redirects'):190+ raise TooManyRedirects()191+192+ # Release the connection back into the pool.193+ r.raw.release_conn()194+195+ history.append(r)196+197+ url = r.headers['location']198+ data = self.data199+ files = self.files200+201+ # 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)205+206+ # 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))213+214+ # 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.method221+222+ # 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 = None227+228+ if (r.status_code == 303) and self.method != 'HEAD':229+ method = 'GET'230+ data = None231+ files = None232+233+ # Remove the cookie headers that were sent.234+ headers = self.headers235+ try:236+ del headers['Cookie']237+ except KeyError:238+ pass239+240+ 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+ )259+260+ request.send()261+ r = request.response262+263+ r.history = history264+265+ self.response = r266+ self.response.request = self267+268+269+ 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))275+276+ def deregister_hook(self, event, hook):277+ """Deregister a previously registered hook.278+ Returns True if the hook existed, False if not.279+ """280+281+ try:282+ self.hooks[event].remove(hook)283+ return True284+ except ValueError:285+ return False286+287+ 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.291+292+ Once a request is successfully sent, `sent` will equal True.293+294+ :param anyway: If True, request will be sent, even if it has295+ already been sent.296+297+ :param prefetch: If not None, will override the request's own setting298+ for prefetch.299+ """300+301+ # Build the URL302+ url = self.full_url303+304+ # Pre-request hook.305+ r = dispatch_hook('pre_request', self.hooks, self)306+ self.__dict__.update(r.__dict__)307+308+ # Logging309+ log.info('Sending %s: %s' % (self, url))310+311+ # 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)314+315+ # 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)319+320+ # # Allow auth to make its changes.321+ # r = self.auth(self)322+323+ # # Update self to reflect the auth changes.324+ # self.__dict__.update(r.__dict__)325+326+ # # Nottin' on you.327+ # body = None328+ # content_type = None329+330+ # # Multi-part file uploads.331+ # if self.files:332+ # (body, content_type) = self._encode_files(self.files)333+ # else:334+ # if self.data:335+336+ # 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'341+342+ # 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))349+350+ # # 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_type353+354+ _p = urlparse(url)355+ no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))356+ proxy = self.proxies.get(_p.scheme)357+358+ 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)368+369+ if not self.config.get('keep_alive'):370+ self.headers['Connection'] = 'close'371+372+ # if url.startswith('https') and self.verify:373+374+ # cert_loc = None375+376+ # # Allow self-specified cert location.377+ # if self.verify is not True:378+ # cert_loc = self.verify379+380+ # # Look for configuration.381+ # if not cert_loc and self.config.get('trust_env'):382+ # cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')383+384+ # # Curl compatibility.385+ # if not cert_loc and self.config.get('trust_env'):386+ # cert_loc = os.environ.get('CURL_CA_BUNDLE')387+388+ # if not cert_loc:389+ # cert_loc = DEFAULT_CA_BUNDLE_PATH390+391+ # if not cert_loc:392+ # raise Exception("Could not find a suitable SSL CA certificate bundle.")393+394+ # conn.cert_reqs = 'CERT_REQUIRED'395+ # conn.ca_certs = cert_loc396+ # else:397+ # conn.cert_reqs = 'CERT_NONE'398+ # conn.ca_certs = None399+400+ # 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.cert406+407+ if not self.sent or anyway:408+409+ # 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_header414+415+ # Pre-send hook.416+ r = dispatch_hook('pre_send', self.hooks, self)417+ self.__dict__.update(r.__dict__)418+419+ # 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 = True435+436+ # except socket.error as sockerr:437+ # raise ConnectionError(sockerr)438+439+ # except MaxRetryError as e:440+ # raise ConnectionError(e)441+442+ # 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.')449+450+ # build_response can throw TooManyRedirects451+ self._build_response(r)452+453+ # Response manipulation hook.454+ self.response = dispatch_hook('response', self.hooks, self.response)455+456+ # Post-request hook.457+ r = dispatch_hook('post_request', self.hooks, self)458+ self.__dict__.update(r.__dict__)459+460+ # 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.content466+467+ return self.sent468+469+ 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)479+480+ def prepare(self):481+ return deepcopy(self)