本文整理匯總了Python中requests.models.Response方法的典型用法代碼示例。如果您正苦於以下問題:Python models.Response方法的具體用法?Python models.Response怎麽用?Python models.Response使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類requests.models
的用法示例。
在下文中一共展示了models.Response方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def __init__(self, response: Response, url: str, empty: bool = False):
"""Create a new Page object.
@type response: Response
@param response: a requests Response instance.
@type url: str
@param url: URL of the Page.
@type empty: bool
@param empty: whether the Page is empty (body length == 0)"""
self._response = response
self._url = url
self._base = None
self._soup = None
self._is_empty = empty
try:
self._tld = get_tld(url)
except TldDomainNotFound:
self._tld = urlparse(url).netloc
示例2: _interpret_returned_request
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def _interpret_returned_request(self, res, frmt):
# must be a Response
if isinstance(res, Response) is False:
return res
# if a response, there is a status code that should be ok
if not res.ok:
reason = res.reason
self.logging.warning("status is not ok with {0}".format(reason))
return res.status_code
if frmt == "json":
try:
return res.json()
except:
return res
# finally
return res.content
示例3: test
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def test(self):
patience = 100
while True:
try:
response = requests.get("http://localhost:{}".format(self.port))
break
except ConnectionError:
patience -= 1
if not patience:
self.fail(
"Couldn't get response from app, (Python executable {})".format(
sys.executable
)
)
else:
sleep(0.1)
self.assertIsInstance(response, Response)
self.assertIn("Hello There!", response.text)
示例4: _decode_response_as_text_lines
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def _decode_response_as_text_lines(file_uri: str, res: Response) -> Iterator[str]:
"""Decode requests response into utf8 lines
Downloads remote files to disk, rather than streaming directly, to support compressed
files. The python gzip module doesn't support streaming directly and implementing
with zlib seemed more error prone than writing to disk.
"""
suffix = os.path.splitext(file_uri)[1]
if suffix == '.gz':
with NamedTemporaryFile(suffix=suffix) as f_temp:
shutil.copyfileobj(res.raw, f_temp)
f_temp.flush()
with gzip.open(f_temp.name, 'rt') as f_out:
yield from f_out
else:
if res.encoding is None:
res.encoding = 'utf-8'
yield from res.iter_lines(decode_unicode=True)
log.info('Finished download of %s', file_uri)
示例5: on_file_available
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def on_file_available(self, uri: str, response: Response) -> None:
# Metadata we aren't interested in
if os.path.basename(uri)[0] == '_':
return
lines = Peekable(_decode_response_as_text_lines(uri, response))
try:
header = json.loads(lines.peek())
action, meta = header.popitem()
index_name = meta['_index']
except (ValueError, KeyError):
raise MalformedUploadException(
"Loaded file is malformed and cannot be processed: {}".format(uri))
# Ignoring errors, can't do anything useful with them. They still
# get logged and counted.
bulk_import(client=self.client_for_index(index_name),
actions=pair(line.strip() for line in lines),
expand_action_callback=expand_string_actions,
**self.bulk_kwargs)
示例6: test_new_api_object
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def test_new_api_object(self):
def api_client(x): return x
obj = new_api_object(api_client, simple_data)
self.assertIsInstance(obj, APIObject)
self.assertIsNone(obj.response)
self.assertIsNone(obj.pagination)
self.assertIsNone(obj.warnings)
response = Response()
def pagination(x): return x
def warnings(x): return x
obj = new_api_object(
api_client, simple_data, response=response, pagination=pagination,
warnings=warnings)
self.assertIs(obj.response, response)
self.assertIs(obj.pagination, pagination)
self.assertIs(obj.warnings, warnings)
示例7: send
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def send(self, request, **kwargs):
response = Response()
response.headers = {}
response.encoding = 'utf-8' # FIXME: this is a complete guess
response.url = request.url
response.request = request
response.connection = self
try:
response.raw = open(request.url.replace('file://', ''), 'r')
except IOError as e:
response.status_code = 404
return response
response.status_code = 200
return response
示例8: test_from_response_404_with_detail
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def test_from_response_404_with_detail(self):
r = models.Response()
r.status_code = 404
r.headers['Content-Type'] = "application/json"
r._content = json.dumps({
"code": 404,
"description": {
"cause": "Aggregation method does not exist for this metric",
"detail": {
"aggregation_method": "rate:mean",
"metric": "a914dad6-b8f6-42f6-b090-6daa29725caf",
}},
"title": "Not Found"
}).encode('utf-8')
exc = exceptions.from_response(r)
self.assertIsInstance(exc, exceptions.ClientException)
示例9: hashivault_pki_ca_set
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def hashivault_pki_ca_set(module):
params = module.params
client = hashivault_auth_client(params)
mount_point = params.get('mount_point').strip('/')
pem_bundle = params.get('pem_bundle')
# check if engine is enabled
changed, err = check_secrets_engines(module, client)
if err:
return err
result = {'changed': changed}
if module.check_mode:
return result
data = client.secrets.pki.submit_ca_information(pem_bundle=pem_bundle, mount_point=mount_point)
if data:
from requests.models import Response
if isinstance(data, Response):
result['data'] = data.text
else:
result['data'] = data
return result
示例10: get_objects
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def get_objects(self, **filter_kwargs):
self._verify_can_read()
query_params = _filter_kwargs_to_query_params(filter_kwargs)
assert isinstance(query_params, dict)
full_filter = BasicFilter(query_params)
objs = full_filter.process_filter(
self.objects,
("id", "type", "version"),
self.manifests,
100,
)[0]
if objs:
return stix2.v21.Bundle(objects=objs)
else:
resp = Response()
resp.status_code = 404
resp.raise_for_status()
示例11: get_object
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def get_object(self, id, **filter_kwargs):
self._verify_can_read()
query_params = _filter_kwargs_to_query_params(filter_kwargs)
assert isinstance(query_params, dict)
full_filter = BasicFilter(query_params)
# In this endpoint we must first filter objects by id beforehand.
objects = [x for x in self.objects if x["id"] == id]
if objects:
filtered_objects = full_filter.process_filter(
objects,
("version",),
self.manifests,
100,
)[0]
else:
filtered_objects = []
if filtered_objects:
return stix2.v21.Bundle(objects=filtered_objects)
else:
resp = Response()
resp.status_code = 404
resp.raise_for_status()
示例12: test_get_404
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def test_get_404():
"""a TAXIICollectionSource.get() call that receives an HTTP 404 response
code from the taxii2client should be be returned as None.
TAXII spec states that a TAXII server can return a 404 for nonexistent
resources or lack of access. Decided that None is acceptable reponse
to imply that state of the TAXII endpoint.
"""
class TAXIICollection404():
can_read = True
def get_object(self, id, version=None):
resp = Response()
resp.status_code = 404
resp.raise_for_status()
ds = stix2.TAXIICollectionSource(TAXIICollection404())
# this will raise 404 from mock TAXII Client but TAXIICollectionStore
# should handle gracefully and return None
stix_obj = ds.get("indicator--1")
assert stix_obj is None
示例13: get_objects
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def get_objects(self, **filter_kwargs):
self._verify_can_read()
query_params = _filter_kwargs_to_query_params(filter_kwargs)
assert isinstance(query_params, dict)
full_filter = BasicFilter(query_params)
objs = full_filter.process_filter(
self.objects,
("id", "type", "version"),
self.manifests,
100,
)[0]
if objs:
return stix2.v20.Bundle(objects=objs)
else:
resp = Response()
resp.status_code = 404
resp.raise_for_status()
示例14: get_object
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def get_object(self, id, **filter_kwargs):
self._verify_can_read()
query_params = _filter_kwargs_to_query_params(filter_kwargs)
assert isinstance(query_params, dict)
full_filter = BasicFilter(query_params)
# In this endpoint we must first filter objects by id beforehand.
objects = [x for x in self.objects if x["id"] == id]
if objects:
filtered_objects = full_filter.process_filter(
objects,
("version",),
self.manifests,
100,
)[0]
else:
filtered_objects = []
if filtered_objects:
return stix2.v20.Bundle(objects=filtered_objects)
else:
resp = Response()
resp.status_code = 404
resp.raise_for_status()
示例15: test_searchParamIsNoneAndResopnseCodeIs200_shouldReturnAllOrgCollections
# 需要導入模塊: from requests import models [as 別名]
# 或者: from requests.models import Response [as 別名]
def test_searchParamIsNoneAndResopnseCodeIs200_shouldReturnAllOrgCollections(self, mock_api_get):
org_id = "org_id"
# self.search_response.
result = ['col1','col2','col3']
response_mock = MagicMock(spec=Response, status_code=200, headers={'content-type': "application/json"}
, text=json.dumps({'status': True,"facets": {
"dates": {},
"fields": {},
"queries": {}
},"results": result
}))
response_mock.json.return_value = result
mock_api_get.return_value = response_mock
orgReadBaseView = views.OrganizationReadBaseView()
orgReadBaseView.request = FakeRequest()
searcher = orgReadBaseView.get_org_collections(org_id, search_params={'resourceFilter':'col'})
self.assertEquals(searcher.search_results, result)