本文整理匯總了Python中aiohttp.ServerDisconnectedError方法的典型用法代碼示例。如果您正苦於以下問題:Python aiohttp.ServerDisconnectedError方法的具體用法?Python aiohttp.ServerDisconnectedError怎麽用?Python aiohttp.ServerDisconnectedError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類aiohttp
的用法示例。
在下文中一共展示了aiohttp.ServerDisconnectedError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_single_proxy
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def test_single_proxy(self, proxy):
"""
text one proxy, if valid, put them to usable_proxies.
"""
try:
async with aiohttp.ClientSession() as session:
try:
if isinstance(proxy, bytes):
proxy = proxy.decode('utf-8')
real_proxy = 'http://' + proxy
print('Testing', proxy)
async with session.get(self.test_api, proxy=real_proxy, timeout=get_proxy_timeout) as response:
if response.status == 200:
self._conn.put(proxy)
print('Valid proxy', proxy)
except (ProxyConnectionError, TimeoutError, ValueError):
print('Invalid proxy', proxy)
except (ServerDisconnectedError, ClientResponseError,ClientConnectorError) as s:
print(s)
pass
示例2: fetch
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def fetch(self):
while True:
try:
hdrlen = constants.STREAM_HEADER_SIZE_BYTES
header = yield from self._response.content.readexactly(hdrlen)
_, length = struct.unpack(">BxxxL", header)
if not length:
continue
data = yield from self._response.content.readexactly(length)
except (
aiohttp.ClientConnectionError,
aiohttp.ServerDisconnectedError,
asyncio.IncompleteReadError,
):
break
return data
示例3: add_safe
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def add_safe(self, name, url, author_id):
"""Try to add an emote. Returns a string that should be sent to the user."""
if not re.fullmatch(r'\w{2,32}', name, re.ASCII):
return _(
'{name} is not a valid emote name; use 2–32 English letters, numbers and underscores.'
).format(name=discord.utils.escape_mentions(name))
try:
emote = await self.add_from_url(name, url, author_id)
except discord.HTTPException as ex:
return (
_('An error occurred while creating the emote:\n')
+ utils.format_http_exception(ex))
except ValueError:
return _('Error: Invalid URL.')
except aiohttp.ServerDisconnectedError:
return _('Error: The connection was closed early by the remote host.')
except aiohttp.ClientResponseError as exc:
raise errors.HTTPException(exc.status)
else:
return _('Emote {emote} successfully created.').format(emote=emote)
示例4: _get
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def _get(self, url, data=None, headers=None, method='GET'):
page = ''
try:
timeout = aiohttp.ClientTimeout(total=self._timeout)
async with self._sem_provider, self._session.request(
method, url, data=data, headers=headers, timeout=timeout
) as resp:
page = await resp.text()
if resp.status != 200:
log.debug(
'url: %s\nheaders: %s\ncookies: %s\npage:\n%s'
% (url, resp.headers, resp.cookies, page)
)
raise BadStatusError('Status: %s' % resp.status)
except (
UnicodeDecodeError,
BadStatusError,
asyncio.TimeoutError,
aiohttp.ClientOSError,
aiohttp.ClientResponseError,
aiohttp.ServerDisconnectedError,
) as e:
page = ''
log.debug('%s is failed. Error: %r;' % (url, e))
return page
示例5: fetch
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def fetch(self, url):
"""Fetch request."""
error_msg = None
try:
async with aiohttp.ClientSession() as session:
body = await self.fetch_with_session(session, url)
except asyncio.TimeoutError:
error_msg = 'Request timed out'
raise ClashRoyaleAPIError(message=error_msg)
except aiohttp.ServerDisconnectedError as err:
error_msg = 'Server disconnected error: {}'.format(err)
raise ClashRoyaleAPIError(message=error_msg)
except (aiohttp.ClientError, ValueError) as err:
error_msg = 'Request connection error: {}'.format(err)
raise ClashRoyaleAPIError(message=error_msg)
except json.JSONDecodeError:
error_msg = "Non JSON returned"
raise ClashRoyaleAPIError(message=error_msg)
else:
return body
finally:
if error_msg is not None:
raise ClashRoyaleAPIError(message=error_msg)
示例6: target_fetch
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def target_fetch(url, headers, timeout=15):
"""
:param url: target url
:return: text
"""
with async_timeout.timeout(timeout):
try:
async with aiohttp.ClientSession() as client:
async with client.get(url, headers=headers) as response:
assert response.status == 200
LOGGER.info('Task url: {}'.format(response.url))
try:
text = await response.text()
except:
try:
text = await response.read()
except aiohttp.ServerDisconnectedError as e:
LOGGER.exception(e)
text = None
return text
except Exception as e:
LOGGER.exception(str(e))
return None
示例7: _arequest
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def _arequest(self, url, **params):
method = params.get('method', 'GET')
json_data = params.get('json', {})
timeout = params.pop('timeout', None) or self.timeout
try:
async with self.session.request(
method, url, timeout=timeout, headers=self.headers, params=params, data=json_data
) as resp:
return self._raise_for_status(resp, await resp.text())
except asyncio.TimeoutError:
raise NotResponding
except aiohttp.ServerDisconnectedError:
raise NetworkError
示例8: _arequest
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def _arequest(self, url, **params):
timeout = params.pop('timeout', None) or self.timeout
try:
async with self.session.get(url, timeout=timeout, headers=self.headers, params=params) as resp:
return self._raise_for_status(resp, await resp.text())
except asyncio.TimeoutError:
raise NotResponding
except aiohttp.ServerDisconnectedError:
raise NetworkError
示例9: fail_with_disconnected_error
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def fail_with_disconnected_error():
raise aiohttp.ServerDisconnectedError("Darn it, can't connect")
示例10: handle_exception
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def handle_exception():
"""
Context manager translating network related exceptions
to custom :mod:`~galaxy.api.errors`.
"""
try:
yield
except asyncio.TimeoutError:
raise BackendTimeout()
except aiohttp.ServerDisconnectedError:
raise BackendNotAvailable()
except aiohttp.ClientConnectionError:
raise NetworkError()
except aiohttp.ContentTypeError:
raise UnknownBackendResponse()
except aiohttp.ClientResponseError as error:
if error.status == HTTPStatus.UNAUTHORIZED:
raise AuthenticationRequired()
if error.status == HTTPStatus.FORBIDDEN:
raise AccessDenied()
if error.status == HTTPStatus.SERVICE_UNAVAILABLE:
raise BackendNotAvailable()
if error.status == HTTPStatus.TOO_MANY_REQUESTS:
raise TooManyRequests()
if error.status >= 500:
raise BackendError()
if error.status >= 400:
logging.warning(
"Got status %d while performing %s request for %s",
error.status, error.request_info.method, str(error.request_info.url)
)
raise UnknownError()
except aiohttp.ClientError:
logging.exception("Caught exception while performing request")
raise UnknownError()
示例11: __anext__
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def __anext__(self):
while True:
try:
data = yield from self._response.content.readline()
if not data:
break
except (aiohttp.ClientConnectionError, aiohttp.ServerDisconnectedError):
break
return self._transform(json.loads(data.decode("utf8")))
raise StopAsyncIteration
示例12: run
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def run(self, **params):
if self.response:
warnings.warn("already running", RuntimeWarning, stackelevel=2)
return
forced_params = {"follow": True}
default_params = {"stdout": True, "stderr": True}
params = ChainMap(forced_params, params, default_params)
try:
self.response = await self.docker._query(
"containers/{self.container._id}/logs".format(self=self), params=params
)
while True:
msg = await self.response.content.readline()
if not msg:
break
await self.channel.publish(msg)
except (aiohttp.ClientConnectionError, aiohttp.ServerDisconnectedError):
pass
finally:
# signal termination to subscribers
await self.channel.publish(None)
try:
await self.response.release()
except Exception:
pass
self.response = None
示例13: test_body_match
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def test_body_match(aresponses):
aresponses.add("foo.com", "/", "get", aresponses.Response(text="hi"), body_pattern=re.compile(r".*?apple.*"))
url = "http://foo.com"
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, data={"fruit": "pineapple"}) as response:
text = await response.text()
assert text == "hi"
except ServerDisconnectedError:
pass
aresponses.assert_plan_strictly_followed()
示例14: test_failure_no_match
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def test_failure_no_match(aresponses):
async with aiohttp.ClientSession() as session:
try:
async with session.get("http://foo.com") as response:
await response.text()
except ServerDisconnectedError:
pass
with pytest.raises(NoRouteFoundError):
aresponses.assert_all_requests_matched()
with pytest.raises(NoRouteFoundError):
aresponses.assert_plan_strictly_followed()
示例15: fetch_multi
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ServerDisconnectedError [as 別名]
def fetch_multi(self, urls):
"""Perform parallel fetch"""
results = []
error_msg = None
try:
async with aiohttp.ClientSession() as session:
for url in urls:
await asyncio.sleep(0)
body = await self.fetch_with_session(session, url)
results.append(body)
except asyncio.TimeoutError:
error_msg = 'Request timed out'
raise ClashRoyaleAPIError(message=error_msg)
except aiohttp.ServerDisconnectedError as err:
error_msg = 'Server disconnected error: {}'.format(err)
raise ClashRoyaleAPIError(message=error_msg)
except (aiohttp.ClientError, ValueError) as err:
error_msg = 'Request connection error: {}'.format(err)
raise ClashRoyaleAPIError(message=error_msg)
except json.JSONDecodeError:
error_msg = "Non JSON returned"
raise ClashRoyaleAPIError(message=error_msg)
else:
return results
finally:
if error_msg is not None:
raise ClashRoyaleAPIError(message=error_msg)