def _on_request(self, request, **kwargs): match = self._find_match(request) # TODO(dcramer): find the correct class for this if match is None: error_msg = 'Connection refused: {0}'.format(request.url) response = ConnectionError(error_msg) self._calls.add(request, response) raise response headers = { 'Content-Type': match['content_type'], } if match['adding_headers']: headers.update(match['adding_headers']) response = HTTPResponse( status=match['status'], body=BufferIO(match['body']), headers=headers, preload_content=False, ) adapter = HTTPAdapter() response = adapter.build_response(request, response) if not match['stream']: response.content # NOQA self._calls.add(request, response) return response
def _on_request(self, request, **kwargs): match = self._find_match(request) # TODO(dcramer): find the correct class for this if match is None: raise ConnectionError('Connection refused') headers = { 'Content-Type': match['content_type'], } if match['adding_headers']: headers.update(match['adding_headers']) response = HTTPResponse( status=match['status'], body=StringIO(match['body']), headers=headers, preload_content=False, ) adapter = HTTPAdapter() r = adapter.build_response(request, response) if not match['stream']: r.content # NOQA return r
def build_response_from_raw_bytes(data: bytes) -> Response: urllib_response = RestService.urllib3_response_from_bytes(data) adapter = HTTPAdapter() requests_response = adapter.build_response(requests.PreparedRequest(), urllib_response) # actual content of response needs to be set explicitly requests_response._content = urllib_response.data return requests_response
def send(self, request, **kwargs): if (self._is_cache_disabled or request.method not in self._cache_allowable_methods): response = super(CachedSession, self).send(request, **kwargs) response.from_cache = False return response cache_key = self.cache.create_key(request) def send_request_and_cache_response(): if self._deny_outbound: print(request.url) raise Exception(("ERROR: OutBound communication was attempted," " but deny_outbound was set to True")) cache_response = True response = super(CachedSession, self).send(request, **kwargs) if response.status_code in self._cache_allowable_codes: # # Special case for cblr: # if we get a status of pending then don't cache # try: if request.url.find( 'cblr') != -1 and request.method == 'GET': if isinstance(response.json(), dict) and response.json().get( 'status', '') == 'pending': cache_response = False except: cache_response = True if cache_response: self.cache.save_response(cache_key, response) response.from_cache = False return response response = self.cache.get_response(cache_key) if response is None: return send_request_and_cache_response() if 'Content-Encoding' in response.headers: del response.headers['Content-Encoding'] adapter = HTTPAdapter() response = adapter.build_response(request, response) # dispatch hook here, because we've removed it before pickling response.from_cache = True response = dispatch_hook('response', request.hooks, response, **kwargs) return response
def send(self, request, **kwargs): if (self._is_cache_disabled or request.method not in self._cache_allowable_methods): response = super(CachedSession, self).send(request, **kwargs) response.from_cache = False return response cache_key = self.cache.create_key(request) def send_request_and_cache_response(): if self._deny_outbound: print(request.url) raise Exception(("ERROR: OutBound communication was attempted," " but deny_outbound was set to True")) cache_response = True response = super(CachedSession, self).send(request, **kwargs) if response.status_code in self._cache_allowable_codes: # # Special case for cblr: # if we get a status of pending then don't cache # try: if request.url.find('cblr') != -1 and request.method == 'GET': if isinstance(response.json(), dict) and response.json().get('status', '') == 'pending': cache_response = False except: cache_response = True if cache_response: self.cache.save_response(cache_key, response) response.from_cache = False return response response = self.cache.get_response(cache_key) if response is None: return send_request_and_cache_response() if 'Content-Encoding' in response.headers: del response.headers['Content-Encoding'] adapter = HTTPAdapter() response = adapter.build_response(request, response) # dispatch hook here, because we've removed it before pickling response.from_cache = True response = dispatch_hook('response', request.hooks, response, **kwargs) return response
def _on_request(self, request, **kwargs): match = self._find_match(request) # TODO(dcramer): find the correct class for this if match is None: error_msg = 'Connection refused: {0}'.format(request.url) response = ConnectionError(error_msg) self._calls.add(request, response) raise response if 'body' in match and isinstance(match['body'], Exception): self._calls.add(request, match['body']) raise match['body'] headers = { 'Content-Type': match['content_type'], } if 'callback' in match: # use callback status, r_headers, body = match['callback'](request) body = BufferIO(body.encode('utf-8')) headers.update(r_headers) elif 'body' in match: if match['adding_headers']: headers.update(match['adding_headers']) status = match['status'] body = BufferIO(match['body']) response = HTTPResponse( status=status, body=body, headers=headers, preload_content=False, ) adapter = HTTPAdapter() response = adapter.build_response(request, response) if not match.get('stream'): response.content # NOQA self._calls.add(request, response) return response
def call_salesforce(url, method, session, headers, **kwargs): """Utility that generates a request to salesforce using urllib3 instead of requests package. This is necessary for connections that use the mutual authentication with encrypted certificates, the package requests can't handle it. PrepareRequest and HttpAdapter are used so that it returns a regular Response <requests.Response> that is expected for the rest of the process. """ additional_headers = kwargs.pop('additional_headers', dict()) headers.update(additional_headers or dict()) request_args = {'method': method.upper(), 'headers': headers} context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) # We will try and load the cert file and pass from the environment variables cert_file = os.environ.get('SIMPLE_SALESFORCE_CERT_FILE', None) cert_pass = os.environ.get('SIMPLE_SALESFORCE_PASSWORD', None) if cert_file and cert_pass: context.load_cert_chain(certfile=cert_file, password=cert_pass) request = PreparedRequest() parsed = urlparse(url) parsed = parsed._replace(netloc="{}:{}".format(parsed.hostname, 8443)) request.prepare(url=parsed.geturl(), data=kwargs.get('data') or {}, **request_args) http = PoolManager(ssl_context=context, cert_reqs='CERT_REQUIRED') result = http.urlopen(url=request.url, body=request.body, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, **request_args) adapter = HTTPAdapter() response = adapter.build_response(request, result) if response.status_code >= 300: from simple_salesforce.util import exception_handler exception_handler(response) adapter.close() return response
def send( self, request: requests.models.PreparedRequest, stream: bool = False, timeout: Union[None, float, Tuple[float, float], Tuple[float, None]] = None, verify: Union[bool, str] = True, cert: Union[None, Union[bytes, Text], Container[Union[bytes, Text]]] = None, proxies: Optional[Mapping[str, str]] = None, ) -> requests.models.Response: try: # This is very similar to the parser in # urllib.request.DataHandler in the standard library. assert request.url scheme, data_str = request.url.split(':', 1) mediatype, data_str = data_str.split(',', 1) data_bytes = unquote_to_bytes(data_str) if mediatype.endswith(';base64'): data_bytes = base64.decodebytes(data_bytes) mediatype = mediatype[:-len(';base64')] if not mediatype: mediatype = "text/plain;charset=US-ASCII" except BaseException as err: raise InvalidURL(err, request=request) # Now pack that info in to a urllib3.response.HTTPResponse. u3resp = HTTPResponse( status=200, reason='OK', headers={ 'Content-Type': mediatype, 'Content-Length': str(len(data_bytes)), }, body=io.BytesIO(data_bytes), ) # Now pack that info in to a requests.models.Response. return HTTPAdapter.build_response(cast(HTTPAdapter, self), request, u3resp)
def build_response(self, request, rv): content, status, headers = rv if content: fh = BytesIO(content[0]) for chunk in content: fh.write(chunk) fh.seek(0) content = fh else: content = BytesIO() code, reason = status.split(None, 1) resp = HTTPResponse(body=content, headers=headers, status=int(code), version=10, reason=reason, preload_content=False, original_response=MockResponse(headers)) return HTTPAdapter.build_response(self, request, resp)