本文整理汇总了Python中requests.RequestException方法的典型用法代码示例。如果您正苦于以下问题:Python requests.RequestException方法的具体用法?Python requests.RequestException怎么用?Python requests.RequestException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.RequestException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _fetch_access_token
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def _fetch_access_token(self, url, params):
""" The real fetch access token """
logger.info("Fetching access token")
res = self._http.get(url=url, params=params)
try:
res.raise_for_status()
except requests.RequestException as reqe:
raise WeChatClientException(
errcode=None, errmsg=None, client=self, request=reqe.request, response=reqe.response,
)
result = res.json()
if "errcode" in result and result["errcode"] != 0:
raise WeChatClientException(
result["errcode"], result["errmsg"], client=self, request=res.request, response=res,
)
expires_in = 7200
if "expires_in" in result:
expires_in = result["expires_in"]
self.session.set(self.access_token_key, result["access_token"], expires_in)
self.expires_at = int(time.time()) + expires_in
return result
示例2: _request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def _request(self, method, url_or_endpoint, **kwargs):
if not url_or_endpoint.startswith(("http://", "https://")):
api_base_url = kwargs.pop("api_base_url", self.API_BASE_URL)
url = f"{api_base_url}{url_or_endpoint}"
else:
url = url_or_endpoint
if "params" not in kwargs:
kwargs["params"] = {}
if isinstance(kwargs["params"], dict) and "component_access_token" not in kwargs["params"]:
kwargs["params"]["component_access_token"] = self.access_token
if isinstance(kwargs["data"], dict):
kwargs["data"] = json.dumps(kwargs["data"])
res = self._http.request(method=method, url=url, **kwargs)
try:
res.raise_for_status()
except requests.RequestException as reqe:
raise WeChatClientException(
errcode=None, errmsg=None, client=self, request=reqe.request, response=reqe.response,
)
return self._handle_result(res, method, url, **kwargs)
示例3: _push_to_registry
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def _push_to_registry(self, namespace, repository, release, bundle, auth_token):
push_uri = 'https://quay.io/cnr/api/v1/packages/%s/%s' % (namespace, repository)
logger.info('Pushing bundle to %s' % push_uri)
headers = {'Content-Type': 'application/json', 'Authorization': auth_token}
json = {'blob': bundle, 'release': release, "media_type": "helm"}
try:
r = requests.post(push_uri, json=json, headers=headers)
except requests.RequestException as e:
msg = str(e)
logger.error(msg)
raise OpCourierQuayCommunicationError(msg)
if r.status_code != 200:
logger.error(r.text)
try:
r_json = r.json()
except ValueError:
r_json = {}
msg = r_json.get('error', {}).get(
'message', 'Failed to get error details.'
)
raise OpCourierQuayErrorResponse(msg, r.status_code, r_json)
示例4: test_base_raise_exception_not_requests_response_object
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def test_base_raise_exception_not_requests_response_object(mock_requests):
mock_requests().delete.side_effect = [requests.RequestException()]
with pytest.raises(nomad.api.exceptions.BaseNomadException) as excinfo:
n = nomad.Nomad(
host="162.16.10.102",
port=common.NOMAD_PORT,
timeout=0.001,
verify=False
)
_ = n.job.deregister_job("example")
# excinfo is a ExceptionInfo instance, which is a wrapper around the actual exception raised.
# The main attributes of interest are .type, .value and .traceback.
# https://docs.pytest.org/en/3.0.1/assert.html#assertions-about-expected-exceptions
assert hasattr(excinfo.value.nomad_resp, "text") is False
assert isinstance(excinfo.value.nomad_resp, requests.RequestException)
assert "raised due" in str(excinfo)
示例5: request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def request(self, request, timeout=None):
try:
timeout = timeout or self.transport_timeout
with self.transport.settings(timeout=timeout):
method = self.get_method(request.method_name)
result = method(*request.args, **request.kwargs)
except zeep.exceptions.Fault as fault:
self.logger.exception("Fault")
error, code = parse_tbk_error_message(fault.message)
raise SoapServerException(error, code, request)
except RequestException as error:
self.logger.exception("Request exception")
raise SoapRequestException(error, request)
else:
serialized = zeep.helpers.serialize_object(result)
last_sent = self.get_last_sent_envelope()
last_received = self.get_last_received_envelope()
return serialized, last_sent, last_received
示例6: bot
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def bot(message: str, user_config: dict):
if config['enable_bot'] and user_config['bot_notice']:
try:
group_id = user_config['group_id']
except KeyError:
group_id = config['group_id']
# 传入JSON时,应使用这个UA
headers = {'Content-Type': 'application/json',
'Authorization': f'Bearer {config["bot_token"]}'}
for _group_id in group_id:
_msg = {
'group_id': int(_group_id),
'message': message,
'auto_escape': False
}
msg = json.dumps(_msg)
logger = logging.getLogger('run.bot')
try:
requests.post(f'http://{config["bot_host"]}/send_group_msg', data=msg, headers=headers)
logger.warning(f'{msg}')
except requests.exceptions.RequestException as e:
logger.exception(e)
示例7: request_html
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def request_html(url, method='GET', headers=None, proxies=None):
"""
:param url:
:param method:
:param headers:
:param proxies:
:return:
"""
resp = None
try:
r = requests.request(method, url, headers=headers, proxies=proxies)
if r.status_code == 200:
resp = r.text
except requests.RequestException as e:
print(e)
return resp
示例8: get_password
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def get_password(self, hash_start: str) -> list:
"""
:param hash_start: The first 5 characters of a SHA1 hash
:return: A list of hashes that match the hash_start param
"""
BASE_URl = 'https://api.pwnedpasswords.com/range/'
url = BASE_URl + hash_start
try:
response = requests.get(url)
except requests.RequestException as e:
self.logger.error(e)
raise
hash_list = response.text.splitlines()
hash_list = [hash_start + hash_ for hash_ in hash_list]
hash_list = [hash_[:40] for hash_ in hash_list]
return hash_list
示例9: retry
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def retry(retries=5, delay=2.0,
exc_types=(OperationalError, RequestException)):
def decorator(func):
def f_retry(*args, **kwargs):
for i in range(retries):
try:
return func(*args, **kwargs)
except exc_types as exc:
if i < retries - 1:
logger.info('%s failed (attempt %d of %d)',
func.__name__, i + 1, retries)
logger.debug('Caught exception, retrying...',
exc_info=True)
time.sleep(delay)
else:
logger.exception('Failed after %d attempts', retries)
if isinstance(exc, RequestException):
logger.debug('Response was: %r', exc.response.text)
raise
return f_retry
return decorator
示例10: retry
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def retry(retries=5, delay=2.0,
exc_types=(RetriableConnectionFailure, RequestException)):
def decorator(func):
def f_retry(*args, **kwargs):
for i in range(retries):
try:
return func(*args, **kwargs)
except exc_types as exc:
if i < retries - 1:
logger.debug('Caught exception, retrying...',
exc_info=True)
time.sleep(delay)
else:
logger.exception('Failed after %d attempts', retries)
if isinstance(exc, RequestException):
logger.debug('Response was: %r', exc.response.text)
raise
return f_retry
return decorator
示例11: retry
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def retry(retries=5, delay=2.0, exc_types=(RequestException,)):
def decorator(func):
def f_retry(*args, **kwargs):
for i in range(retries):
try:
return func(*args, **kwargs)
except exc_types as exc:
if i < retries - 1:
logger.debug('Caught exception, retrying...',
exc_info=True)
time.sleep(delay)
else:
logger.exception('Failed after %d attempts', retries)
if isinstance(exc, RequestException):
logger.debug('Response was: %r', exc.response.text)
raise
return f_retry
return decorator
示例12: get
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def get(self, endpoint, return_response=False, **kwargs):
"""Send HTTP GET to the endpoint.
:arg str endpoint: The endpoint to send to.
:arg bool return_response: If true will also return the response
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
"""
args = self.translate_kwargs(**kwargs)
response = self.session.get(self.make_url(endpoint), **args)
decoded_response = _decode_response(response)
if return_response:
return decoded_response, response
return decoded_response
示例13: put
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def put(self, endpoint, return_response=False, **kwargs):
"""Send HTTP PUT to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
"""
args = self.translate_kwargs(**kwargs)
response = self.session.put(self.make_url(endpoint), **args)
decoded_response = _decode_response(response)
if return_response:
return decoded_response, response
return decoded_response
示例14: post
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def post(self, endpoint, return_response=False, **kwargs):
"""Send HTTP POST to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
"""
args = self.translate_kwargs(**kwargs)
response = self.session.post(self.make_url(endpoint), **args)
decoded_response = _decode_response(response)
if return_response:
return decoded_response, response
return decoded_response
示例15: delete
# 需要导入模块: import requests [as 别名]
# 或者: from requests import RequestException [as 别名]
def delete(self, endpoint, return_response=False, **kwargs):
"""Send HTTP DELETE to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
"""
args = self.translate_kwargs(**kwargs)
response = self.session.delete(self.make_url(endpoint), **args)
decoded_response = _decode_response(response)
if return_response:
return decoded_response, response
return decoded_response