Skip to content
Myr

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

4 files+538 added−35 removed

modified:requests/adapters.py-2 removed
115 unmodified lines
116 # extract_cookies_to_jar(self.cookies, self, resp)117118119120121120 def close(self):121 """Dispose of any internal state.122123 Currently, this just closes the PoolManager, which closes pooled
51 unmodified lines
modified:requests/api.py+2 added-5 removed
43 unmodified lines
44 if session is None:45 session = sessions.session(config=kwargs.get('config', None))46 adhoc_session = True4748 try:49 return session.request(method=method, url=url, **kwargs)50 finally:51 if adhoc_session:52 session.close()4849 return session.request(method=method, url=url, **kwargs)505152def get(url, **kwargs):53 """Sends a GET request. Returns :class:`Response` object.5455 :param url: URL for the new :class:`Request` object.
70 unmodified lines
modified:requests/models.py+492 added-2 removed
15 unmodified lines
16from datetime import datetime17from io import BytesIO1819from .hooks import dispatch_hook, HOOKS20zz20from .structures import CaseInsensitiveDict21from .status_codes import codes2223from .auth import HTTPBasicAuth, HTTPProxyAuth24from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header
146 unmodified lines
171 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 = hooks
178 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 # return365366 # 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)850851852class BaseResponse(object):853 """The basic Respone"""854 def __init__(self):855 self.url = None
206 unmodified lines
1062 """Returns the parsed header links of the response, if any."""10631064 header = self.headers['link']10651066 # l = MultiDict()1067 l = {}10681069 if header:1070 links = parse_header_links(header)
22 unmodified lines
modified:requests/sessions.py+44 added-26 removed
17 unmodified lines
18from .utils import header_expand, from_key_val_list19from .packages.urllib3.poolmanager import PoolManager202122from adapters import HTTPAdapter2324def merge_kwargs(local_kwarg, default_kwarg):25 """Merges kwarg dictionaries.2627 If a local key in the dictionary is set to None, it will be removed.
87 unmodified lines
115116 for (k, v) in list(defaults.items()):117 self.config.setdefault(k, deepcopy(v))118117 self.init_poolmanager()118119 # 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)124125 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 )131132 def __repr__(self):133 return '<requests-client at 0x%x>' % (id(self))134125 def __enter__(self):126 return self127128 def __exit__(self, *args):129 self.close()130131 def close(self):142 """Dispose of any internal state.132 pass133144 Currently, this just closes the PoolManager, which closes pooled145 connections.146 """147 self.poolmanager.clear()148134 def request(self, method, url,135 params=None,136 data=None,137 headers=None,
9 unmodified lines
147 prefetch=None,148 verify=None,149 cert=None):150151 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 = hooks164165 prep = req.prepare()166167 return self.send(prep)168169170171172 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):188189 """Constructs and sends a :class:`Request <Request>`.190 Returns :class:`Response <Response>` object.191192 :param method: method for the new :class:`Request` object.
97 unmodified lines
290291 # Send the HTTP Request.292 return self._send_request(r, **args)293271 def _send_request(self, r, **kwargs):272 # Send the request.273 r.send(prefetch=kwargs.get("prefetch"))274275 # Return the response.276 return r.response277294 def get(self, url, **kwargs):295 """Sends a GET request. Returns :class:`Response` object.296297 :param url: URL for the new :class:`Request` object.
63 unmodified lines
361 return self.request('delete', url, **kwargs)362363 def send(self, request):364 """Send a given PreparedRequest."""349 return request.send()365 adapter = HTTPAdapter()366 r = adapter.send(request)367 return r368369 def __getstate__(self):370 return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)371
11 unmodified lines