本文整理汇总了Python中requests.HTTPError方法的典型用法代码示例。如果您正苦于以下问题:Python requests.HTTPError方法的具体用法?Python requests.HTTPError怎么用?Python requests.HTTPError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.HTTPError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_batch_log
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def get_batch_log(
self, batch_id: int, from_: int = None, size: int = None
) -> Optional[BatchLog]:
"""Get logs for a batch.
:param batch_id: The ID of the batch.
:param from_: The line number to start getting logs from.
:param size: The number of lines of logs to get.
"""
params = {}
if from_ is not None:
params["from"] = from_
if size is not None:
params["size"] = size
try:
data = self._client.get(f"/batches/{batch_id}/log", params=params)
except requests.HTTPError as e:
if e.response.status_code == 404:
return None
else:
raise
return BatchLog.from_json(data)
示例2: test_extract_link
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def test_extract_link(self):
success_response = {'success': True, 'data': 'link'}
responses.add(responses.POST, constants.ENDPOINTS['extract_link'],
json=success_response,
status=200)
responses.add(responses.POST, constants.ENDPOINTS['extract_link'],
status=401)
# success call
result = utils.extract_link(self.session, 'https://www.ojbk.com')
self.assertEqual(result, 'link')
self.assertEqual(len(responses.calls), 1)
self.assertEqual(responses.calls[0].request.url, constants.ENDPOINTS['extract_link'])
self.assertEqual(responses.calls[0].response.json(), success_response)
# failed call
with self.assertRaises(requests.HTTPError) as cm:
utils.extract_link(self.session, 'https://www.ojbk.com')
self.assertEqual(len(responses.calls), 2)
self.assertEqual(cm.exception.response.status_code, 401)
示例3: test_create_my_post
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def test_create_my_post(self):
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {'success': True, 'data': {}}
mock_response.raise_for_status.return_value = None
self.mock_jike_session.post.return_value = mock_response
result = self.jike_client.create_my_post('jike')
self.assertIsInstance(result, tuple)
# failed by post no string content
with self.assertRaises(AssertionError):
self.jike_client.create_my_post(123)
# failed call by post both link and picture at one time
with self.assertRaises(ValueError):
self.jike_client.create_my_post('jike', link='a', pictures='b')
mock_response.reset_mock()
# failed call by post failed
mock_response.json.return_value = {'success': False}
with self.assertRaises(RuntimeError):
self.jike_client.create_my_post('jike')
# failed call by server error
mock_response.status_code = 401
mock_response.raise_for_status.side_effect = requests.HTTPError()
with self.assertRaises(requests.HTTPError):
self.jike_client.create_my_post('jike')
示例4: test_delete_my_post
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def test_delete_my_post(self):
mock_message = Mock()
mock_message.type = 'ORIGINAL_POST'
mock_message.id = '123'
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {'success': True}
mock_response.raise_for_status.return_value = None
self.mock_jike_session.post.return_value = mock_response
result = self.jike_client.delete_my_post(mock_message)
self.assertTrue(result)
# failed call by no post id provided
with self.assertRaises(AssertionError):
self.jike_client.delete_my_post(None)
# failed call by server error
mock_response.status_code = 403
mock_response.raise_for_status.side_effect = requests.HTTPError()
with self.assertRaises(requests.HTTPError):
self.jike_client.delete_my_post(mock_message)
示例5: test__collect_action
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def test__collect_action(self):
mock_message = Mock()
mock_message.type = 'OFFICIAL_MESSAGE'
mock_message.id = '123'
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {'success': True}
mock_response.raise_for_status.return_value = None
self.mock_jike_session.post.return_value = mock_response
result = self.jike_client._collect_action(mock_message, 'collect_it')
self.assertTrue(result)
# failed call by assertion
mock_message.type = ''
with self.assertRaises(AssertionError):
self.jike_client._collect_action(mock_message, 'uncollect_it')
# failed by server error
mock_message.type = 'ORIGINAL_POST'
mock_response.status_code = 403
mock_response.raise_for_status.side_effect = requests.HTTPError()
with self.assertRaises(requests.HTTPError):
self.jike_client._collect_action(mock_message, 'collect_it')
示例6: _update_case_description
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def _update_case_description(self, attributes: JsonDict, case_id: str, name: str,
references: Optional[str]) -> None:
""" Update test case description in TestRail
*Args:* \n
_attributes_ - attributes of test case in Robot Framework;\n
_case_id_ - case id;\n
_name_ - test case name;\n
_references_ - test references.
"""
logger.info(f"[TestRailListener] update of test {case_id} in TestRail")
description = f"{attributes['doc']}\nPath to test: {attributes['longname']}"
request_fields: Dict[str, Union[str, int, None]] = {
'title': name, 'type_id': self.TESTRAIL_CASE_TYPE_ID_AUTOMATED,
'custom_case_description': description, 'refs': references}
try:
json_result = self.tr_client.update_case(case_id, request_fields)
result = json.dumps(json_result, sort_keys=True, indent=4)
logger.info(f"[TestRailListener] result for method update_case: {result}")
except requests.HTTPError as error:
logger.error(f"[TestRailListener] http error, while execute request:\n{error}")
示例7: raise_for_status
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def raise_for_status(self, allow_redirects=True):
"""Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""
if self.status_code == 304:
return
elif self.error:
if self.traceback:
six.reraise(Exception, Exception(self.error), Traceback.from_string(self.traceback).as_traceback())
http_error = HTTPError(self.error)
elif (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
http_error = HTTPError('%s Redirection' % (self.status_code))
elif (self.status_code >= 400) and (self.status_code < 500):
http_error = HTTPError('%s Client Error' % (self.status_code))
elif (self.status_code >= 500) and (self.status_code < 600):
http_error = HTTPError('%s Server Error' % (self.status_code))
else:
return
http_error.response = self
raise http_error
示例8: test_location_google_breaks
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def test_location_google_breaks(self):
"""User passed location arg but google api gave error"""
caught_exceptions = [
requests.ConnectionError, requests.HTTPError, requests.Timeout]
with mock.patch('requests.get') as mock_get:
for exception in caught_exceptions:
mock_get.side_effect = exception
with capture_sys_output():
with self.assertRaises(RipeAtlasToolsException):
cmd = Command()
cmd.init_args(["--location", "blaaaa"])
cmd.run()
mock_get.side_effect = Exception()
with self.assertRaises(Exception):
cmd = Command()
cmd.init_args(["--location", "blaaaa"])
cmd.run()
示例9: show_manifest
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def show_manifest(self, client, repository, ref):
try:
repo = client.repository(repository)
except requests.HTTPError as e:
if e.response.status_code == requests.codes.not_found:
print("Repository {0} not found".format(repository))
else:
raise
else:
assert client.api_version in [1, 2]
if client.api_version == 2:
manifest, digest = repo.manifest(ref)
print("Digest: {0}".format(digest))
print("Manifest:")
print(json.dumps(manifest, indent=2, sort_keys=True))
else:
image = repo.image(ref)
image_json = image.get_json()
print("Image ID: {0}".format(image.image_id))
print("Image JSON:")
print(json.dumps(image_json, indent=2, sort_keys=True))
示例10: _generic_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def _generic_request(self, reqfunction, rest_query, data=None):
# if the data is a dictionary, it has to be converted to json text
if isinstance(data, dict):
data = json.dumps(data)
# makes sure the base url is the one from the instance
rest_query = rest_query.replace(self._base_url, '')
if not rest_query.startswith('/'):
rest_query = '/' + rest_query
logger_.debug(self._base_url + rest_query)
r = reqfunction(self._base_url + rest_query, stream=True, headers=self._headers, data=data)
if r and r.status_code in (200, 201):
return json.loads(r.text)
elif r and r.status_code == 204:
return
else:
logger_.error(self._base_url + rest_query)
logger_.error(r.text)
raise(requests.HTTPError(r))
示例11: login
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def login(self, username, password, require_ownership=False):
resp = self.session.post(
self.login_url,
params=dict(require_game_ownership=int(require_ownership)),
data=dict(username=username, password=password)
)
try:
json = resp.json()
except Exception:
json = None
try:
resp.raise_for_status()
return json[0]
except requests.HTTPError:
if isinstance(json, dict) and 'message' in json:
if json['message'] == "Insufficient membership":
raise OwnershipError(json['message'])
else:
raise AuthError(json['message'])
else:
raise
示例12: run
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def run(self, params={}):
input_classification = params.get("classification")
offset = params.get("offset")
limit = params.get("limit")
params = dict()
if input_classification is not None:
params["classification"] = input_classification
params["offset"] = offset
params["limit"] = limit
try:
response = self.connection.CLIENT.get(self.__URL, params=params)
applications = response.json()["items"]
applications = komand.helper.clean(applications)
except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
raise error
return {"applications": applications}
示例13: run
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def run(self, params={}):
name = params.get("name")
q = params.get("q")
offset = params.get("offset")
limit = params.get("limit")
params = dict()
if name is not None:
params["name"] = name
if q is not None:
params["q"] = q
params["offset"] = offset
params["limit"] = limit
try:
response = self.connection.CLIENT.get(self.__URL, params=params)
entries = response.json()["items"]
entries = komand.helper.clean(entries)
except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
raise error
return {"entries": entries}
示例14: run
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def run(self, params={}):
user_principal_name = params.get(Input.USER_PRINCIPAL_NAME)
token = self.connection.access_token
base_url = 'https://graph.microsoft.com/beta/users/%s' % user_principal_name
headers = {'Authorization': 'Bearer %s' % token}
try:
response = requests.delete(base_url, headers=headers)
except requests.HTTPError:
raise PluginException(cause=f"There was an issue with the Delete User request. Double-check the username: {user_principal_name}",
data=response.text)
if response.status_code == 204:
success = True
return {Output.SUCCESS: success}
else:
raise PluginException(cause="The response from Office365 indicated something went wrong: {response.status_code}",
data=response.text)
示例15: run
# 需要导入模块: import requests [as 别名]
# 或者: from requests import HTTPError [as 别名]
def run(self, params={}):
user_principal_name = params.get(Input.USER_PRINCIPAL_NAME)
location = params.get(Input.LOCATION)
token = self.connection.access_token
base_url = "https://graph.microsoft.com/v1.0/users/%s" % user_principal_name
headers = {"Authorization": "Bearer %s" % token, "Content-Type": "application/json",}
body = {
"usageLocation": location
}
try:
response = requests.patch(base_url, json=body, headers=headers)
except requests.HTTPError:
raise PluginException(cause=f"There was an issue updating the user's location. Double-check the user name: {user_principal_name}",
data=response.text)
if response.status_code == 204:
return {Output.SUCCESS: True}
else:
raise PluginException(f"The response from Office365 indicated something went wrong: {response.status_code}",
data=response.text)