当前位置: 首页>>代码示例>>Python>>正文


Python aiohttp.ServerDisconnectedError方法代码示例

本文整理汇总了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 
开发者ID:Germey,项目名称:ProxyPool,代码行数:22,代码来源:schedule.py

示例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 
开发者ID:aio-libs,项目名称:aiodocker,代码行数:22,代码来源:multiplexed.py

示例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) 
开发者ID:EmoteBot,项目名称:EmoteCollector,代码行数:22,代码来源:emote.py

示例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 
开发者ID:constverum,项目名称:ProxyBroker,代码行数:27,代码来源:providers.py

示例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) 
开发者ID:smlbiobot,项目名称:SML-Cogs,代码行数:25,代码来源:racf_audit.py

示例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 
开发者ID:howie6879,项目名称:owllook,代码行数:25,代码来源:function.py

示例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 
开发者ID:cgrok,项目名称:clashroyale,代码行数:15,代码来源:client.py

示例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 
开发者ID:cgrok,项目名称:clashroyale,代码行数:11,代码来源:client.py

示例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") 
开发者ID:madedotcom,项目名称:atomicpuppy,代码行数:4,代码来源:test_fetching.py

示例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() 
开发者ID:TouwaStar,项目名称:Galaxy_Plugin_Bethesda,代码行数:37,代码来源:http.py

示例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 
开发者ID:aio-libs,项目名称:aiodocker,代码行数:13,代码来源:jsonstream.py

示例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 
开发者ID:aio-libs,项目名称:aiodocker,代码行数:28,代码来源:logs.py

示例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() 
开发者ID:CircleUp,项目名称:aresponses,代码行数:15,代码来源:test_server.py

示例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() 
开发者ID:CircleUp,项目名称:aresponses,代码行数:14,代码来源:test_server.py

示例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) 
开发者ID:smlbiobot,项目名称:SML-Cogs,代码行数:29,代码来源:racf_audit.py


注:本文中的aiohttp.ServerDisconnectedError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。