本文整理匯總了Python中requests.exceptions.Timeout方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.Timeout方法的具體用法?Python exceptions.Timeout怎麽用?Python exceptions.Timeout使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類requests.exceptions
的用法示例。
在下文中一共展示了exceptions.Timeout方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_pod_relay_preferences
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def get_pod_relay_preferences(self, host):
"""Query remote pods on https first, fall back to http."""
logging.info("Querying %s" % host)
try:
try:
response = requests.get("https://%s/.well-known/x-social-relay" % host,
timeout=5,
headers={"User-Agent": config.USER_AGENT})
except timeout:
response = None
if not response or response.status_code != 200:
response = requests.get("http://%s/.well-known/x-social-relay" % host,
timeout=5,
headers={"User-Agent": config.USER_AGENT})
if response.status_code != 200:
return None
except (ConnectionError, Timeout, timeout):
return None
try:
# Make sure we have a valid x-social-relay doc
validate(response.json(), self.schema)
return response.text
except (ValueError, ValidationError):
return None
示例2: requests_get
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def requests_get(url, **kwargs):
USER_AGENTS = (
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0',
'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) '
'Chrome/19.0.1084.46 Safari/536.5'),
('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46'
'Safari/536.5')
)
try:
r = requests.get(
url,
timeout=12,
headers={'User-Agent': random.choice(USER_AGENTS)}, **kwargs
)
except ConnectionError:
exit_after_echo('Network connection failed.')
except Timeout:
exit_after_echo('timeout.')
return r
示例3: get_search_results
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def get_search_results(self, video):
results = OrderedDict()
for i, downloader in enumerate(self.downloader):
try:
result = downloader.get_subtitles(video, sub_num=self.sub_num)
results.update(result)
except ValueError as e:
print("error: " + str(e))
except (exceptions.Timeout, exceptions.ConnectionError):
print("connect timeout, search next site.")
if i == (len(self.downloader) - 1):
print("PLEASE CHECK YOUR NETWORK STATUS")
sys.exit(0)
else:
continue
# TODO: search all sites or exit after collecting enough results
if len(results) >= self.sub_num:
break
return results
示例4: request
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def request(self, url, *args, **kwargs):
try:
stream = HttpStream(url, *args, verbose=self.verbose, **kwargs)
if kwargs.get('stream', False):
return stream
with stream as s:
content = s.req.content
return HttpResponse(s.status_code, s.headers, content)
# Timeout will catch both ConnectTimout and ReadTimeout
except (RetryError, Timeout) as ex:
raise OsbsNetworkException(url, str(ex), '',
cause=ex, traceback=sys.exc_info()[2])
except HTTPError as ex:
raise OsbsNetworkException(url, str(ex), ex.response.status_code,
cause=ex, traceback=sys.exc_info()[2])
except Exception as ex:
raise OsbsException(cause=ex, traceback=sys.exc_info()[2])
示例5: post
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def post(self, *args, **kwargs):
"""Straightforward wrapper around `requests.Session.post
<http://docs.python-requests.org/en/master/api/#requests.Session.post>`__.
:return: `requests.Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`__
object with a *soup*-attribute added by :func:`_add_soup`.
"""
try:
response = self.session.post(*args, **kwargs)
self._update_state(response)
return response
except Timeout:
self.timeout_exception = True
print(f'Timeout exception.')
resp = Response()
resp.status_code = 408
self._update_state(resp)
return resp
示例6: test_gather_logs_failed
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def test_gather_logs_failed(self, mock_post, mock_get, mock_logger):
"""SalesforceApp - Gather event logs but log files returns empty"""
self.set_config_values(
'CLIENT_ID', 'CLIENT_SECRET', 'USERNAME', 'PASSWORD', 'SECURITY_TOKEN'
)
self._app._instance_url = 'MY_URL'
mock_post.return_value = Mock(
status_code=200,
json=Mock(return_value={'access_token': 'AUTH_TOKEN', 'instance_url': 'MY_URL'})
)
mock_get.return_value = Mock(
status_code=200,
json=Mock(side_effect=[list_salesforce_api_versions(), Timeout])
)
assert_equal(self._app._gather_logs(), None)
mock_logger.assert_called_once()
mock_get.return_value = Mock(
status_code=204,
json=Mock(return_value={'errorCode': 'ERROR_CODE', 'message': 'error message'})
)
assert_equal(self._app._gather_logs(), None)
示例7: test_do_api_call_succeeds_after_retrying
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def test_do_api_call_succeeds_after_retrying(self):
for exception in [requests_exceptions.ConnectionError,
requests_exceptions.SSLError,
requests_exceptions.Timeout,
requests_exceptions.ConnectTimeout,
requests_exceptions.HTTPError]:
with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
with mock.patch.object(self.hook.log, 'error') as mock_errors:
setup_mock_requests(
mock_requests,
exception,
error_count=2,
response_content={'run_id': '1'}
)
response = self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})
self.assertEqual(mock_errors.call_count, 2)
self.assertEqual(response, {'run_id': '1'})
示例8: test_do_api_call_waits_between_retries
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def test_do_api_call_waits_between_retries(self, mock_sleep):
retry_delay = 5
self.hook = DatabricksHook(retry_delay=retry_delay)
for exception in [requests_exceptions.ConnectionError,
requests_exceptions.SSLError,
requests_exceptions.Timeout,
requests_exceptions.ConnectTimeout,
requests_exceptions.HTTPError]:
with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
with mock.patch.object(self.hook.log, 'error'):
mock_sleep.reset_mock()
setup_mock_requests(mock_requests, exception)
with self.assertRaises(AirflowException):
self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})
self.assertEqual(len(mock_sleep.mock_calls), self.hook.retry_limit - 1)
calls = [
mock.call(retry_delay),
mock.call(retry_delay)
]
mock_sleep.assert_has_calls(calls)
示例9: exception_handle
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def exception_handle(method):
"""Handle exception raised by requests library."""
def wrapper(*args, **kwargs):
try:
result = method(*args, **kwargs)
return result
except ProxyError:
LOG.exception('ProxyError when try to get %s.', args)
raise ProxyError('A proxy error occurred.')
except ConnectionException:
LOG.exception('ConnectionError when try to get %s.', args)
raise ConnectionException('DNS failure, refused connection, etc.')
except Timeout:
LOG.exception('Timeout when try to get %s', args)
raise Timeout('The request timed out.')
except RequestException:
LOG.exception('RequestException when try to get %s.', args)
raise RequestException('Please check out your network.')
return wrapper
示例10: get_my_public_url
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def get_my_public_url():
if 'PUBLIC_URL' in os.environ:
return os.environ['PUBLIC_URL']
try:
if os.environ.get('PORT', '80') != '80':
port = ':' + os.environ.get('PORT', '80')
else:
port = ''
ip = get('http://ip.42.pl/raw').text
has_public_address = get(
f'http://{ip}{port}/ping'
).text == 'pong'
except (ConnectionError, Timeout):
return None
if has_public_address:
return f'http://{ip}{port}'
else:
return None
示例11: test_broadcast_block_raise_exception
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def test_broadcast_block_raise_exception(
fx_session: scoped_session, fx_user: User,
error: typing.Union[ConnectionError, Timeout]
):
block = Block.create(fx_user, [])
url = 'http://test.neko'
now = datetime.datetime.utcnow()
node = Node(url=url, last_connected_at=now)
fx_session.add(node)
fx_session.flush()
with Mocker() as m:
m.post('http://test.neko/blocks', exc=error)
multicast(
serialized=block.serialize(
use_bencode=False,
include_suffix=True,
include_moves=True,
include_hash=True
),
broadcast=broadcast_block,
)
assert node.last_connected_at == now
示例12: _login
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def _login(self):
"""
Login to the xqueue server
"""
try:
self.session = requests.Session()
self.session.auth = (self.auth_user, self.auth_pass)
request = self.session.post('{0}/xqueue/login/'.format(self.url),
data={'username': self.queue_user,
'password': self.queue_pass})
response = json.loads(request.text)
if response['return_code'] != 0:
raise Exception("Invalid return code in reply resp:{0}".format(
str(response)))
except (Exception, ConnectionError, Timeout) as e:
log.critical("Unable to connect to queue xqueue: {0}".format(e))
raise
示例13: get_length
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def get_length(self):
"""
Returns the length of the queue
"""
try:
request = self.session.get('{0}/xqueue/get_queuelen/'.format(
self.url), params={'queue_name': self.queue_name})
response = json.loads(request.text)
if response['return_code'] != 0:
raise Exception("Invalid return code in reply")
length = int(response['content'])
except (ValueError, Exception, ConnectionError, Timeout) as e:
log.critical("Unable to get queue length: {0}".format(e))
raise
return length
示例14: get_submission
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def get_submission(self):
"""
Gets a single submission from the xqueue
server and returns the payload as a dictionary
"""
try:
request = self.session.get('{0}/xqueue/get_submission/'.format(
self.url), params={'queue_name': self.queue_name})
except (ConnectionError, Timeout) as e:
log.critical("Unable to get submission from queue xqueue: {0}".format(e))
raise
try:
response = json.loads(request.text)
log.debug('response from get_submission: {0}'.format(response))
if response['return_code'] != 0:
log.critical("response: {0}".format(request.text))
raise Exception("Invalid return code in reply")
return json.loads(response['content'])
except (Exception, ValueError, KeyError) as e:
log.critical("Unable to parse xqueue message: {0} response: {1}".format(e, request.text))
raise
示例15: _DoHttpRequestAsync
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import Timeout [as 別名]
def _DoHttpRequestAsync(self, sink_stack, deadline, stream, msg):
if deadline:
timeout = deadline - time.time()
if timeout < 0:
sink_stack.AsyncProcessResponseMessage(MethodReturnMessage(error=TimeoutError()))
else:
timeout = None
try:
response = self._MakeRequest(msg, stream, timeout)
if self._raise_on_http_error and 400 <= response.status_code < 600:
err_text = 'HTTP Error %d: %s.' % (response.status_code, response.reason)
if response.text:
err_text += '\nThe server returned:\n%s' % response.text
err = exceptions.HTTPError(err_text, response=response)
msg = MethodReturnMessage(error=err)
else:
self._ProcessResponse(response, sink_stack)
return
except exceptions.Timeout:
msg = MethodReturnMessage(error=TimeoutError())
except Exception as ex:
msg = MethodReturnMessage(error=ex)
sink_stack.AsyncProcessResponseMessage(msg)