backup.py
This file
Path
backup.py
604 lines · 20.9 KiB · Python
Last changed by
cleanupKenneth Reitzbefore adoption4a01272
History of this fileTake it
12 def old_request(self, method, url,3 params=None,4 data=None,5 headers=None,6 cookies=None,7 files=None,8 auth=None,9 timeout=None,10 allow_redirects=True,11 proxies=None,12 hooks=None,13 return_response=True,14 config=None,15 prefetch=None,16 verify=None,17 cert=None):1819 """Constructs and sends a :class:`Request <Request>`.20 Returns :class:`Response <Response>` object.2122 :param method: method for the new :class:`Request` object.23 :param url: URL for the new :class:`Request` object.24 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.25 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.26 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.27 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.28 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.29 :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.30 :param timeout: (optional) Float describing the timeout of the request.31 :param allow_redirects: (optional) Boolean. Set to True by default.32 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.33 :param return_response: (optional) If False, an un-sent Request object will returned.34 :param config: (optional) A configuration dictionary. See ``request.defaults`` for allowed keys and their default values.35 :param prefetch: (optional) whether to immediately download the response content. Defaults to ``True``.36 :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.37 :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.38 """3940 method = str(method).upper()4142 # Default empty dicts for dict params.43 data = [] if data is None else data44 files = [] if files is None else files45 headers = {} if headers is None else headers46 params = {} if params is None else params47 hooks = {} if hooks is None else hooks48 prefetch = prefetch if prefetch is not None else self.prefetch4950 # use session's hooks as defaults51 for key, cb in list(self.hooks.items()):52 hooks.setdefault(key, cb)5354 # Expand header values.55 if headers:56 for k, v in list(headers.items() or {}):57 headers[k] = header_expand(v)5859 args = dict(60 method=method,61 url=url,62 data=data,63 params=from_key_val_list(params),64 headers=from_key_val_list(headers),65 cookies=cookies,66 files=files,67 auth=auth,68 hooks=from_key_val_list(hooks),69 timeout=timeout,70 allow_redirects=allow_redirects,71 proxies=from_key_val_list(proxies),72 config=from_key_val_list(config),73 prefetch=prefetch,74 verify=verify,75 cert=cert,76 _poolmanager=self.poolmanager77 )7879 # merge session cookies into passed-in ones80 dead_cookies = None81 # passed-in cookies must become a CookieJar:82 if not isinstance(cookies, cookielib.CookieJar):83 args['cookies'] = cookiejar_from_dict(cookies)84 # support unsetting cookies that have been passed in with None values85 # this is only meaningful when `cookies` is a dict ---86 # for a real CookieJar, the client should use session.cookies.clear()87 if cookies is not None:88 dead_cookies = [name for name in cookies if cookies[name] is None]89 # merge the session's cookies into the passed-in cookies:90 for cookie in self.cookies:91 args['cookies'].set_cookie(cookie)92 # remove the unset cookies from the jar we'll be using with the current request93 # (but not from the session's own store of cookies):94 if dead_cookies is not None:95 for name in dead_cookies:96 remove_cookie_by_name(args['cookies'], name)9798 # Merge local kwargs with session kwargs.99 for attr in self.__attrs__:100 # we already merged cookies:101 if attr == 'cookies':102 continue103104 session_val = getattr(self, attr, None)105 local_val = args.get(attr)106 args[attr] = merge_kwargs(local_val, session_val)107108 # Arguments manipulation hook.109 args = dispatch_hook('args', args['hooks'], args)110111 # Create the (empty) response.112 r = Request(**args)113114 # Give the response some context.115 r.session = self116117 # Don't send if asked nicely.118 if not return_response:119 return r120121 # Send the HTTP Request.122 return self._send_request(r, **args)123124125class OldRequest(object):126 """The :class:`Request <Request>` object. It carries out all functionality127 of Requests. Recommended interface is with the Requests functions.128 """129130 def __init__(self,131 url=None,132 headers=dict(),133 files=None,134 method=None,135 data=dict(),136 params=dict(),137 auth=None,138 cookies=None,139 timeout=None,140 redirect=False,141 allow_redirects=False,142 proxies=None,143 hooks=None,144 config=None,145 prefetch=True,146 _poolmanager=None,147 verify=None,148 session=None,149 cert=None):150151 #: Dictionary of configurations for this request.152 self.config = dict(config or [])153154 #: Float describes the timeout of the request.155 # (Use socket.setdefaulttimeout() as fallback)156 self.timeout = timeout157158 # URL159160 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.161 self.headers = dict(headers or [])162163 #: Dictionary of files to multipart upload (``{filename: content}``).164 self.files = None165166 #: HTTP Method to use.167 self.method = method168169 #: Dictionary, bytes or file stream of request body data to attach to the170 #: :class:`Request <Request>`.171 self.data = None172173 #: Dictionary of querystring data to attach to the174 #: :class:`Request <Request>`. The dictionary values can be lists for representing175 #: multivalued query parameters.176 self.params = None177178 #: True if :class:`Request <Request>` is part of a redirect chain (disables history179 #: and HTTPError storage).180 self.redirect = redirect181182 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)183 self.allow_redirects = allow_redirects184185 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})186 self.proxies = dict(proxies or [])187188 for proxy_type, uri_ref in list(self.proxies.items()):189 if not uri_ref:190 del self.proxies[proxy_type]191192 # If no proxies are given, allow configuration by environment variables193 # HTTP_PROXY and HTTPS_PROXY.194 if not self.proxies and self.config.get('trust_env'):195 self.proxies = get_environ_proxies(self.url)196197 self.data = data198 self.params = params199 self.files = files200201 #: :class:`Response <Response>` instance, containing202 #: content and metadata of HTTP Response, once :attr:`sent <send>`.203 self.response = Response()204205 #: Authentication tuple or object to attach to :class:`Request <Request>`.206 self.auth = auth207208 # #: CookieJar to attach to :class:`Request <Request>`.209 # if isinstance(cookies, cookielib.CookieJar):210 # self.cookies = cookies211 # else:212 # self.cookies = cookiejar_from_dict(cookies)213214 #: True if Request has been sent.215 self.sent = False216217 #: Event-handling hooks.218 self.hooks = {}219220 for event in HOOKS:221 self.hooks[event] = []222223 hooks = hooks or {}224225 for (k, v) in list(hooks.items()):226 self.register_hook(event=k, hook=v)227228 #: Session.229 self.session = session230231 #: SSL Verification.232 self.verify = verify233234 #: SSL Certificate235 self.cert = cert236237 #: Prefetch response content238 self.prefetch = prefetch239240 # if headers:241 # headers = CaseInsensitiveDict(self.headers)242 # else:243 # headers = CaseInsensitiveDict()244245 # Add configured base headers.246 for (k, v) in list(self.config.get('base_headers', {}).items()):247 if k not in headers:248 headers[k] = v249250 self.headers = headers251 self._poolmanager = _poolmanager252253 def __repr__(self):254 return '<Request [%s]>' % (self.method)255256 def _build_response(self, resp):257 """Build internal :class:`Response <Response>` object258 from given response.259 """260261 def build(resp):262263 response = Response()264265 # Pass settings over.266 response.config = self.config267268 if resp:269270 # Fallback to None if there's no status_code, for whatever reason.271 # response.status_code = getattr(resp, 'status', None)272273 # Make headers case-insensitive.274 # response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))275276 # Set encoding.277 # response.encoding = get_encoding_from_headers(response.headers)278279 # Add new cookies from the server.280 extract_cookies_to_jar(self.cookies, self, resp)281282 # Save cookies in Response.283 response.cookies = self.cookies284285 # Save cookies in Session.286 for cookie in self.cookies:287 self.session.cookies.set_cookie(cookie)288289 # No exceptions were harmed in the making of this request.290 response.error = getattr(resp, 'error', None)291292 # Save original response for later.293 response.raw = resp294 if isinstance(self.full_url, bytes):295 response.url = self.full_url.decode('utf-8')296 else:297 response.url = self.full_url298299 return response300301 history = []302303 r = build(resp)304 # TODO: session level shit305 if r.status_code in REDIRECT_STATI and not self.redirect:306307 while (('location' in r.headers and r.status_code in REDIRECT_STATI) and308 ((r.status_code is codes.see_other) or (self.allow_redirects))):309310 r.content # Consume socket so it can be released311312 if not len(history) < self.config.get('max_redirects'):313 raise TooManyRedirects()314315 # Release the connection back into the pool.316 r.raw.release_conn()317318 history.append(r)319320 url = r.headers['location']321 data = self.data322 files = self.files323324 # Handle redirection without scheme (see: RFC 1808 Section 4)325 if url.startswith('//'):326 parsed_rurl = urlparse(r.url)327 url = '%s:%s' % (parsed_rurl.scheme, url)328329 # Facilitate non-RFC2616-compliant 'location' headers330 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')331 if not urlparse(url).netloc:332 url = urljoin(r.url,333 # Compliant with RFC3986, we percent334 # encode the url.335 requote_uri(url))336337 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4338 if r.status_code is codes.see_other:339 method = 'GET'340 data = None341 files = None342 else:343 method = self.method344345 # Do what the browsers do, despite standards...346 if r.status_code in (codes.moved, codes.found) and self.method == 'POST':347 method = 'GET'348 data = None349 files = None350351 if (r.status_code == 303) and self.method != 'HEAD':352 method = 'GET'353 data = None354 files = None355356 # Remove the cookie headers that were sent.357 headers = self.headers358 try:359 del headers['Cookie']360 except KeyError:361 pass362363 request = Request(364 url=url,365 headers=headers,366 files=files,367 method=method,368 params=self.session.params,369 auth=self.auth,370 cookies=self.cookies,371 redirect=True,372 data=data,373 config=self.config,374 timeout=self.timeout,375 _poolmanager=self._poolmanager,376 proxies=self.proxies,377 verify=self.verify,378 session=self.session,379 cert=self.cert,380 prefetch=self.prefetch381 )382383 request.send()384 r = request.response385386 r.history = history387388 self.response = r389 self.response.request = self390391392 def register_hook(self, event, hook):393 """Properly register a hook."""394 if isinstance(hook, collections.Callable):395 self.hooks[event].append(hook)396 elif hasattr(hook, '__iter__'):397 self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))398399 def deregister_hook(self, event, hook):400 """Deregister a previously registered hook.401 Returns True if the hook existed, False if not.402 """403404 try:405 self.hooks[event].remove(hook)406 return True407 except ValueError:408 return False409410 def send(self, anyway=False, prefetch=None):411 """Sends the request. Returns True if successful, False if not.412 If there was an HTTPError during transmission,413 self.response.status_code will contain the HTTPError code.414415 Once a request is successfully sent, `sent` will equal True.416417 :param anyway: If True, request will be sent, even if it has418 already been sent.419420 :param prefetch: If not None, will override the request's own setting421 for prefetch.422 """423424 # Build the URL425 url = self.full_url426427 # Pre-request hook.428 r = dispatch_hook('pre_request', self.hooks, self)429 self.__dict__.update(r.__dict__)430431 # Logging432 log.info('Sending %s: %s' % (self, url))433434 # Use .netrc auth if none was provided.435 if not self.auth and self.config.get('trust_env'):436 self.auth = get_netrc_auth(url)437438 # if self.auth:439 # if isinstance(self.auth, tuple) and len(self.auth) == 2:440 # # special-case basic HTTP auth441 # self.auth = HTTPBasicAuth(*self.auth)442443 # # Allow auth to make its changes.444 # r = self.auth(self)445446 # # Update self to reflect the auth changes.447 # self.__dict__.update(r.__dict__)448449 # # Nottin' on you.450 # body = None451 # content_type = None452453 # # Multi-part file uploads.454 # if self.files:455 # (body, content_type) = self._encode_files(self.files)456 # else:457 # if self.data:458459 # body = self._encode_params(self.data)460 # if isinstance(self.data, str) or isinstance(self.data, builtin_str) or hasattr(self.data, 'read'):461 # content_type = None462 # else:463 # content_type = 'application/x-www-form-urlencoded'464465 # self.headers['Content-Length'] = '0'466 # if hasattr(body, 'seek') and hasattr(body, 'tell'):467 # body.seek(0, 2)468 # self.headers['Content-Length'] = str(body.tell())469 # body.seek(0, 0)470 # elif body is not None:471 # self.headers['Content-Length'] = str(len(body))472473 # # Add content-type if it wasn't explicitly provided.474 # if (content_type) and (not 'content-type' in self.headers):475 # self.headers['Content-Type'] = content_type476477 _p = urlparse(url)478 no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))479 proxy = self.proxies.get(_p.scheme)480481 if proxy and not any(map(_p.hostname.endswith, no_proxy)):482 conn = poolmanager.ProxyManager(self.get_connection_for_url(proxy))483 _proxy = urlparse(proxy)484 if '@' in _proxy.netloc:485 auth, url = _proxy.netloc.split('@', 1)486 self.proxy_auth = HTTPProxyAuth(*auth.split(':', 1))487 r = self.proxy_auth(self)488 self.__dict__.update(r.__dict__)489 else:490 conn = self.get_connection_for_url(url)491492 if not self.config.get('keep_alive'):493 self.headers['Connection'] = 'close'494495 # if url.startswith('https') and self.verify:496497 # cert_loc = None498499 # # Allow self-specified cert location.500 # if self.verify is not True:501 # cert_loc = self.verify502503 # # Look for configuration.504 # if not cert_loc and self.config.get('trust_env'):505 # cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')506507 # # Curl compatibility.508 # if not cert_loc and self.config.get('trust_env'):509 # cert_loc = os.environ.get('CURL_CA_BUNDLE')510511 # if not cert_loc:512 # cert_loc = DEFAULT_CA_BUNDLE_PATH513514 # if not cert_loc:515 # raise Exception("Could not find a suitable SSL CA certificate bundle.")516517 # conn.cert_reqs = 'CERT_REQUIRED'518 # conn.ca_certs = cert_loc519 # else:520 # conn.cert_reqs = 'CERT_NONE'521 # conn.ca_certs = None522523 # if self.cert:524 # if len(self.cert) == 2:525 # conn.cert_file = self.cert[0]526 # conn.key_file = self.cert[1]527 # else:528 # conn.cert_file = self.cert529530 if not self.sent or anyway:531532 # Skip if 'cookie' header is explicitly set.533 # if 'cookie' not in self.headers:534 # cookie_header = get_cookie_header(self.cookies, self)535 # if cookie_header is not None:536 # self.headers['Cookie'] = cookie_header537538 # Pre-send hook.539 r = dispatch_hook('pre_send', self.hooks, self)540 self.__dict__.update(r.__dict__)541542 # catch urllib3 exceptions and throw Requests exceptions543 # try:544 # # Send the request.545 # r = conn.urlopen(546 # method=self.method,547 # url=self.path_url,548 # body=body,549 # headers=self.headers,550 # redirect=False,551 # assert_same_host=False,552 # preload_content=False,553 # decode_content=False,554 # retries=self.config.get('max_retries', 0),555 # timeout=self.timeout,556 # )557 # self.sent = True558559 # except socket.error as sockerr:560 # raise ConnectionError(sockerr)561562 # except MaxRetryError as e:563 # raise ConnectionError(e)564565 # except (_SSLError, _HTTPError) as e:566 # if isinstance(e, _SSLError):567 # raise SSLError(e)568 # elif isinstance(e, TimeoutError):569 # raise Timeout(e)570 # else:571 # raise Timeout('Request timed out.')572573 # build_response can throw TooManyRedirects574 self._build_response(r)575576 # Response manipulation hook.577 self.response = dispatch_hook('response', self.hooks, self.response)578579 # Post-request hook.580 r = dispatch_hook('post_request', self.hooks, self)581 self.__dict__.update(r.__dict__)582583 # If prefetch is True, mark content as consumed.584 if prefetch is None:585 prefetch = self.prefetch586 if prefetch:587 # Save the response.588 self.response.content589590 return self.sent591592 def get_connection_for_url(self, url):593 # Check to see if keep_alive is allowed.594 try:595 if self.config.get('keep_alive'):596 conn = self._poolmanager.connection_from_url(url)597 else:598 conn = connectionpool.connection_from_url(url)599 return conn600 except LocationParseError as e:601 raise InvalidURL(e)602603 def prepare(self):604 return deepcopy(self)