ready.
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 957216d · Browse files · 2 files·+1 added−603 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+1 added−603 removed
- other:+1 added−603 removed
Provenance
- Commit
b95ad3f- Tree
ff904ab- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
957216d
2 files changed+1 added−603 removed
deleted:backup.py-603 removed
1-2- 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):18-19- """Constructs and sends a :class:`Request <Request>`.20- Returns :class:`Response <Response>` object.21-22- :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 config: (optional) A configuration dictionary. See ``request.defaults`` for allowed keys and their default values.34- :param prefetch: (optional) whether to immediately download the response content. Defaults to ``True``.35- :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.36- :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.37- """38-39- method = str(method).upper()40-41- # Default empty dicts for dict params.42- data = [] if data is None else data43- files = [] if files is None else files44- headers = {} if headers is None else headers45- params = {} if params is None else params46- hooks = {} if hooks is None else hooks47- prefetch = prefetch if prefetch is not None else self.prefetch48-49- # use session's hooks as defaults50- for key, cb in list(self.hooks.items()):51- hooks.setdefault(key, cb)52-53- # Expand header values.54- if headers:55- for k, v in list(headers.items() or {}):56- headers[k] = header_expand(v)57-58- args = dict(59- method=method,60- url=url,61- data=data,62- params=from_key_val_list(params),63- headers=from_key_val_list(headers),64- cookies=cookies,65- files=files,66- auth=auth,67- hooks=from_key_val_list(hooks),68- timeout=timeout,69- allow_redirects=allow_redirects,70- proxies=from_key_val_list(proxies),71- config=from_key_val_list(config),72- prefetch=prefetch,73- verify=verify,74- cert=cert,75- _poolmanager=self.poolmanager76- )77-78- # merge session cookies into passed-in ones79- dead_cookies = None80- # passed-in cookies must become a CookieJar:81- if not isinstance(cookies, cookielib.CookieJar):82- args['cookies'] = cookiejar_from_dict(cookies)83- # support unsetting cookies that have been passed in with None values84- # this is only meaningful when `cookies` is a dict ---85- # for a real CookieJar, the client should use session.cookies.clear()86- if cookies is not None:87- dead_cookies = [name for name in cookies if cookies[name] is None]88- # merge the session's cookies into the passed-in cookies:89- for cookie in self.cookies:90- args['cookies'].set_cookie(cookie)91- # remove the unset cookies from the jar we'll be using with the current request92- # (but not from the session's own store of cookies):93- if dead_cookies is not None:94- for name in dead_cookies:95- remove_cookie_by_name(args['cookies'], name)96-97- # Merge local kwargs with session kwargs.98- for attr in self.__attrs__:99- # we already merged cookies:100- if attr == 'cookies':101- continue102-103- session_val = getattr(self, attr, None)104- local_val = args.get(attr)105- args[attr] = merge_kwargs(local_val, session_val)106-107- # Arguments manipulation hook.108- args = dispatch_hook('args', args['hooks'], args)109-110- # Create the (empty) response.111- r = Request(**args)112-113- # Give the response some context.114- r.session = self115-116- # Don't send if asked nicely.117- if not return_response:118- return r119-120- # Send the HTTP Request.121- return self._send_request(r, **args)122-123-124-class OldRequest(object):125- """The :class:`Request <Request>` object. It carries out all functionality126- of Requests. Recommended interface is with the Requests functions.127- """128-129- def __init__(self,130- url=None,131- headers=dict(),132- files=None,133- method=None,134- data=dict(),135- params=dict(),136- auth=None,137- cookies=None,138- timeout=None,139- redirect=False,140- allow_redirects=False,141- proxies=None,142- hooks=None,143- config=None,144- prefetch=True,145- _poolmanager=None,146- verify=None,147- session=None,148- cert=None):149-150- #: Dictionary of configurations for this request.151- self.config = dict(config or [])152-153- #: Float describes the timeout of the request.154- # (Use socket.setdefaulttimeout() as fallback)155- self.timeout = timeout156-157- # URL158-159- #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.160- self.headers = dict(headers or [])161-162- #: Dictionary of files to multipart upload (``{filename: content}``).163- self.files = None164-165- #: HTTP Method to use.166- self.method = method167-168- #: Dictionary, bytes or file stream of request body data to attach to the169- #: :class:`Request <Request>`.170- self.data = None171-172- #: Dictionary of querystring data to attach to the173- #: :class:`Request <Request>`. The dictionary values can be lists for representing174- #: multivalued query parameters.175- self.params = None176-177- #: True if :class:`Request <Request>` is part of a redirect chain (disables history178- #: and HTTPError storage).179- self.redirect = redirect180-181- #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)182- self.allow_redirects = allow_redirects183-184- # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})185- self.proxies = dict(proxies or [])186-187- for proxy_type, uri_ref in list(self.proxies.items()):188- if not uri_ref:189- del self.proxies[proxy_type]190-191- # If no proxies are given, allow configuration by environment variables192- # HTTP_PROXY and HTTPS_PROXY.193- if not self.proxies and self.config.get('trust_env'):194- self.proxies = get_environ_proxies(self.url)195-196- self.data = data197- self.params = params198- self.files = files199-200- #: :class:`Response <Response>` instance, containing201- #: content and metadata of HTTP Response, once :attr:`sent <send>`.202- self.response = Response()203-204- #: Authentication tuple or object to attach to :class:`Request <Request>`.205- self.auth = auth206-207- # #: CookieJar to attach to :class:`Request <Request>`.208- # if isinstance(cookies, cookielib.CookieJar):209- # self.cookies = cookies210- # else:211- # self.cookies = cookiejar_from_dict(cookies)212-213- #: True if Request has been sent.214- self.sent = False215-216- #: Event-handling hooks.217- self.hooks = {}218-219- for event in HOOKS:220- self.hooks[event] = []221-222- hooks = hooks or {}223-224- for (k, v) in list(hooks.items()):225- self.register_hook(event=k, hook=v)226-227- #: Session.228- self.session = session229-230- #: SSL Verification.231- self.verify = verify232-233- #: SSL Certificate234- self.cert = cert235-236- #: Prefetch response content237- self.prefetch = prefetch238-239- # if headers:240- # headers = CaseInsensitiveDict(self.headers)241- # else:242- # headers = CaseInsensitiveDict()243-244- # Add configured base headers.245- for (k, v) in list(self.config.get('base_headers', {}).items()):246- if k not in headers:247- headers[k] = v248-249- self.headers = headers250- self._poolmanager = _poolmanager251-252- def __repr__(self):253- return '<Request [%s]>' % (self.method)254-255- def _build_response(self, resp):256- """Build internal :class:`Response <Response>` object257- from given response.258- """259-260- def build(resp):261-262- response = Response()263-264- # Pass settings over.265- response.config = self.config266-267- if resp:268-269- # Fallback to None if there's no status_code, for whatever reason.270- # response.status_code = getattr(resp, 'status', None)271-272- # Make headers case-insensitive.273- # response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))274-275- # Set encoding.276- # response.encoding = get_encoding_from_headers(response.headers)277-278- # Add new cookies from the server.279- extract_cookies_to_jar(self.cookies, self, resp)280-281- # Save cookies in Response.282- response.cookies = self.cookies283-284- # Save cookies in Session.285- for cookie in self.cookies:286- self.session.cookies.set_cookie(cookie)287-288- # No exceptions were harmed in the making of this request.289- response.error = getattr(resp, 'error', None)290-291- # Save original response for later.292- response.raw = resp293- if isinstance(self.full_url, bytes):294- response.url = self.full_url.decode('utf-8')295- else:296- response.url = self.full_url297-298- return response299-300- history = []301-302- r = build(resp)303- # TODO: session level shit304- if r.status_code in REDIRECT_STATI and not self.redirect:305-306- while (('location' in r.headers and r.status_code in REDIRECT_STATI) and307- ((r.status_code is codes.see_other) or (self.allow_redirects))):308-309- r.content # Consume socket so it can be released310-311- if not len(history) < self.config.get('max_redirects'):312- raise TooManyRedirects()313-314- # Release the connection back into the pool.315- r.raw.release_conn()316-317- history.append(r)318-319- url = r.headers['location']320- data = self.data321- files = self.files322-323- # Handle redirection without scheme (see: RFC 1808 Section 4)324- if url.startswith('//'):325- parsed_rurl = urlparse(r.url)326- url = '%s:%s' % (parsed_rurl.scheme, url)327-328- # Facilitate non-RFC2616-compliant 'location' headers329- # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')330- if not urlparse(url).netloc:331- url = urljoin(r.url,332- # Compliant with RFC3986, we percent333- # encode the url.334- requote_uri(url))335-336- # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4337- if r.status_code is codes.see_other:338- method = 'GET'339- data = None340- files = None341- else:342- method = self.method343-344- # Do what the browsers do, despite standards...345- if r.status_code in (codes.moved, codes.found) and self.method == 'POST':346- method = 'GET'347- data = None348- files = None349-350- if (r.status_code == 303) and self.method != 'HEAD':351- method = 'GET'352- data = None353- files = None354-355- # Remove the cookie headers that were sent.356- headers = self.headers357- try:358- del headers['Cookie']359- except KeyError:360- pass361-362- request = Request(363- url=url,364- headers=headers,365- files=files,366- method=method,367- params=self.session.params,368- auth=self.auth,369- cookies=self.cookies,370- redirect=True,371- data=data,372- config=self.config,373- timeout=self.timeout,374- _poolmanager=self._poolmanager,375- proxies=self.proxies,376- verify=self.verify,377- session=self.session,378- cert=self.cert,379- prefetch=self.prefetch380- )381-382- request.send()383- r = request.response384-385- r.history = history386-387- self.response = r388- self.response.request = self389-390-391- def register_hook(self, event, hook):392- """Properly register a hook."""393- if isinstance(hook, collections.Callable):394- self.hooks[event].append(hook)395- elif hasattr(hook, '__iter__'):396- self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))397-398- def deregister_hook(self, event, hook):399- """Deregister a previously registered hook.400- Returns True if the hook existed, False if not.401- """402-403- try:404- self.hooks[event].remove(hook)405- return True406- except ValueError:407- return False408-409- def send(self, anyway=False, prefetch=None):410- """Sends the request. Returns True if successful, False if not.411- If there was an HTTPError during transmission,412- self.response.status_code will contain the HTTPError code.413-414- Once a request is successfully sent, `sent` will equal True.415-416- :param anyway: If True, request will be sent, even if it has417- already been sent.418-419- :param prefetch: If not None, will override the request's own setting420- for prefetch.421- """422-423- # Build the URL424- url = self.full_url425-426- # Pre-request hook.427- r = dispatch_hook('pre_request', self.hooks, self)428- self.__dict__.update(r.__dict__)429-430- # Logging431- log.info('Sending %s: %s' % (self, url))432-433- # Use .netrc auth if none was provided.434- if not self.auth and self.config.get('trust_env'):435- self.auth = get_netrc_auth(url)436-437- # if self.auth:438- # if isinstance(self.auth, tuple) and len(self.auth) == 2:439- # # special-case basic HTTP auth440- # self.auth = HTTPBasicAuth(*self.auth)441-442- # # Allow auth to make its changes.443- # r = self.auth(self)444-445- # # Update self to reflect the auth changes.446- # self.__dict__.update(r.__dict__)447-448- # # Nottin' on you.449- # body = None450- # content_type = None451-452- # # Multi-part file uploads.453- # if self.files:454- # (body, content_type) = self._encode_files(self.files)455- # else:456- # if self.data:457-458- # body = self._encode_params(self.data)459- # if isinstance(self.data, str) or isinstance(self.data, builtin_str) or hasattr(self.data, 'read'):460- # content_type = None461- # else:462- # content_type = 'application/x-www-form-urlencoded'463-464- # self.headers['Content-Length'] = '0'465- # if hasattr(body, 'seek') and hasattr(body, 'tell'):466- # body.seek(0, 2)467- # self.headers['Content-Length'] = str(body.tell())468- # body.seek(0, 0)469- # elif body is not None:470- # self.headers['Content-Length'] = str(len(body))471-472- # # Add content-type if it wasn't explicitly provided.473- # if (content_type) and (not 'content-type' in self.headers):474- # self.headers['Content-Type'] = content_type475-476- _p = urlparse(url)477- no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))478- proxy = self.proxies.get(_p.scheme)479-480- if proxy and not any(map(_p.hostname.endswith, no_proxy)):481- conn = poolmanager.ProxyManager(self.get_connection_for_url(proxy))482- _proxy = urlparse(proxy)483- if '@' in _proxy.netloc:484- auth, url = _proxy.netloc.split('@', 1)485- self.proxy_auth = HTTPProxyAuth(*auth.split(':', 1))486- r = self.proxy_auth(self)487- self.__dict__.update(r.__dict__)488- else:489- conn = self.get_connection_for_url(url)490-491- if not self.config.get('keep_alive'):492- self.headers['Connection'] = 'close'493-494- # if url.startswith('https') and self.verify:495-496- # cert_loc = None497-498- # # Allow self-specified cert location.499- # if self.verify is not True:500- # cert_loc = self.verify501-502- # # Look for configuration.503- # if not cert_loc and self.config.get('trust_env'):504- # cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')505-506- # # Curl compatibility.507- # if not cert_loc and self.config.get('trust_env'):508- # cert_loc = os.environ.get('CURL_CA_BUNDLE')509-510- # if not cert_loc:511- # cert_loc = DEFAULT_CA_BUNDLE_PATH512-513- # if not cert_loc:514- # raise Exception("Could not find a suitable SSL CA certificate bundle.")515-516- # conn.cert_reqs = 'CERT_REQUIRED'517- # conn.ca_certs = cert_loc518- # else:519- # conn.cert_reqs = 'CERT_NONE'520- # conn.ca_certs = None521-522- # if self.cert:523- # if len(self.cert) == 2:524- # conn.cert_file = self.cert[0]525- # conn.key_file = self.cert[1]526- # else:527- # conn.cert_file = self.cert528-529- if not self.sent or anyway:530-531- # Skip if 'cookie' header is explicitly set.532- # if 'cookie' not in self.headers:533- # cookie_header = get_cookie_header(self.cookies, self)534- # if cookie_header is not None:535- # self.headers['Cookie'] = cookie_header536-537- # Pre-send hook.538- r = dispatch_hook('pre_send', self.hooks, self)539- self.__dict__.update(r.__dict__)540-541- # catch urllib3 exceptions and throw Requests exceptions542- # try:543- # # Send the request.544- # r = conn.urlopen(545- # method=self.method,546- # url=self.path_url,547- # body=body,548- # headers=self.headers,549- # redirect=False,550- # assert_same_host=False,551- # preload_content=False,552- # decode_content=False,553- # retries=self.config.get('max_retries', 0),554- # timeout=self.timeout,555- # )556- # self.sent = True557-558- # except socket.error as sockerr:559- # raise ConnectionError(sockerr)560-561- # except MaxRetryError as e:562- # raise ConnectionError(e)563-564- # except (_SSLError, _HTTPError) as e:565- # if isinstance(e, _SSLError):566- # raise SSLError(e)567- # elif isinstance(e, TimeoutError):568- # raise Timeout(e)569- # else:570- # raise Timeout('Request timed out.')571-572- # build_response can throw TooManyRedirects573- self._build_response(r)574-575- # Response manipulation hook.576- self.response = dispatch_hook('response', self.hooks, self.response)577-578- # Post-request hook.579- r = dispatch_hook('post_request', self.hooks, self)580- self.__dict__.update(r.__dict__)581-582- # If prefetch is True, mark content as consumed.583- if prefetch is None:584- prefetch = self.prefetch585- if prefetch:586- # Save the response.587- self.response.content588-589- return self.sent590-591- def get_connection_for_url(self, url):592- # Check to see if keep_alive is allowed.593- try:594- if self.config.get('keep_alive'):595- conn = self._poolmanager.connection_from_url(url)596- else:597- conn = connectionpool.connection_from_url(url)598- return conn599- except LocationParseError as e:600- raise InvalidURL(e)601-602- def prepare(self):603- return deepcopy(self)modified:HISTORY.rst+1 added
9 unmodified lines10 - Switch to Apache 2.0 license11 - Swappable Connection Adapters12 - Mountable Connection Adapters13 - Mutable ProcessedRequest chain14+- /s/prefetch/stream15 - Removal of all configuration16 - Standard library logging17 - Make Reponse.json() callable, not property.18 - Usage of new charade project, which provides python 2 and 3 simultaneous chardet.566 unmodified lines