How to use the aiohttp.ClientError function in aiohttp

To help you get started, we’ve selected a few aiohttp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github home-assistant / home-assistant / tests / components / adguard / test_config_flow.py View on Github external
async def test_connection_error(hass, aioclient_mock):
    """Test we show user form on AdGuard Home connection error."""
    aioclient_mock.get(
        "{}://{}:{}/control/status".format(
            "https" if FIXTURE_USER_INPUT[CONF_SSL] else "http",
            FIXTURE_USER_INPUT[CONF_HOST],
            FIXTURE_USER_INPUT[CONF_PORT],
        ),
        exc=aiohttp.ClientError,
    )

    flow = config_flow.AdGuardHomeFlowHandler()
    flow.hass = hass
    result = await flow.async_step_user(user_input=FIXTURE_USER_INPUT)

    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "user"
    assert result["errors"] == {"base": "connection_error"}
github NabDev / NabBot / cogs / utils / tibia.py View on Github external
async def get_world(name, *, tries=5) -> Optional[World]:
    name = name.strip().title()
    if tries == 0:
        raise errors.NetworkError(f"get_world({name})")
    try:
        world = CACHE_WORLDS[name]
        return world
    except KeyError:
        pass
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(World.get_url_tibiadata(name)) as resp:
                content = await resp.text(encoding='ISO-8859-1')
                world = World.from_tibiadata(content)
    except (aiohttp.ClientError, asyncio.TimeoutError, tibiapy.TibiapyException):
        await asyncio.sleep(config.network_retry_delay)
        return await get_world(name, tries=tries - 1)
    CACHE_WORLDS[name] = world
    return world
github ekonda / kutana / kutana / manager / vk / manager.py View on Github external
data = {k: v for k, v in kwargs.items() if v is not None}

        raw_response = {}

        try:
            async with self.session.post(self.api_url.format(method),
                                         data=data) as response:

                raw_response_text = await response.text()

                raw_response = json.loads(raw_response_text)

                logger.debug("Method: %s; Data: %s; Response: %s", method,
                             data, raw_response)

        except (json.JSONDecodeError, aiohttp.ClientError) as e:
            logger.debug("Method: %s; Data: %s; No response", method, data)

            return VKResponse(
                error=True,
                errors=(("Kutana", str(type(e)) + ": " + str(e)),),
                response=""
            )

        if "error" in raw_response:
            return VKResponse(
                error=True,
                errors=(
                    ("VK_req", raw_response.get("error", "")),
                    ("VK_exe", raw_response.get("execute_errors", ""))
                ),
                response=raw_response.get("response", "")
github btsdigital / pyAitu / pyAitu / bot / api.py View on Github external
async def request(session, token, method, data=None, proxy=None, files=None, **kwargs) -> bool or dict:
    log.debug(f"Making request {method}")

    if files and method == "UploadFile":
        data = _compose_data(data, files)
        try:
            async with session.post(FILE_UPLOAD_URL, data=data, proxy=proxy, headers={"X-BOT-TOKEN": token}, **kwargs) as response:
                return await _check_result(method, response)
        except aiohttp.ClientError as e:
            raise Exception(f"aiohttp client throws an error: {e.__class__.__name__}: {e}")
    elif method in ["SetWebhook", "GetWebhook", "DeleteWebhook"]:
        if method == "GetWebhook":
            try:
                async with session.get(WEBHOOK_INFO_URL, proxy=proxy, headers={"X-BOT-TOKEN": token}, **kwargs) as response:
                    return await _check_result(method, response)
            except aiohttp.ClientError as e:
                raise Exception(f"aiohttp client throws an error: {e.__class__.__name__}: {e}")
        elif method == "SetWebhook":
            try:
                async with session.post(WEBHOOK_INFO_URL, proxy=proxy, json=data, headers={"X-BOT-TOKEN": token}, **kwargs) \
                        as response:
                    return await _check_result(method, response)
            except aiohttp.ClientError as e:
                raise Exception(f"aiohttp client throws an error: {e.__class__.__name__}: {e}")
        elif method == "DeleteWebhook":
github Terrance / IMMP / immp / plug / telegram.py View on Github external
async def _api(self, endpoint, schema=_Schema.api(), **kwargs):
        url = "https://api.telegram.org/bot{}/{}".format(self.config["token"], endpoint)
        log.debug("Making API request to %r", endpoint)
        try:
            async with self.session.post(url, **kwargs) as resp:
                try:
                    json = await resp.json()
                    data = schema(json)
                except ClientResponseError as e:
                    raise TelegramAPIConnectError("Bad response with code: {}"
                                                  .format(resp.status)) from e
        except ClientError as e:
            raise TelegramAPIConnectError("Request failed") from e
        except TimeoutError as e:
            raise TelegramAPIConnectError("Request timed out") from e
        if not data["ok"]:
            raise TelegramAPIRequestError(data["error_code"], data["description"])
        return data["result"]
github madedotcom / photon-pump / photonpump / discovery.py View on Github external
async def fetch_new_gossip(session, seed):
    if not seed:
        return []

    LOG.debug("Fetching gossip from http://%s:%s/gossip", seed.address, seed.port)
    try:
        resp = await session.get(f"http://{seed.address}:{seed.port}/gossip")
        data = await resp.json()

        return read_gossip(data)
    except aiohttp.ClientError:
        LOG.exception(
            "Failed loading gossip from http://%s:%s/gossip", seed.address, seed.port
        )

        return None
github home-assistant / hassio-supervisor / hassio / homeassistant.py View on Github external
try:
                async with getattr(self.sys_websession_ssl, method)(
                    url,
                    data=data,
                    timeout=timeout,
                    json=json,
                    headers=headers,
                    params=params,
                ) as resp:
                    # Access token expired
                    if resp.status == 401 and self.refresh_token:
                        self.access_token = None
                        continue
                    yield resp
                    return
            except (asyncio.TimeoutError, aiohttp.ClientError) as err:
                _LOGGER.error("Error on call %s: %s", url, err)
                break

        raise HomeAssistantAPIError()
github cshuaimin / video-funnel / video_funnel / server.py View on Github external
if request.method == 'HEAD':
        return resp

    await resp.prepare(request)
    async with Funnel(
            url,
            range,
            session,
            block_size,
            piece_size,
    ) as funnel:
        try:
            async for chunk in funnel:
                await resp.write(chunk)
            return resp
        except (aiohttp.ClientError, RangeNotSupportedError) as exc:
            print(exc)
            return web.Response(status=exc.status)
        except asyncio.CancelledError:
            raise
github home-assistant / home-assistant / homeassistant / components / bluesound / media_player.py View on Github external
response = await websession.get(url)

            if response.status == 200:
                result = await response.text()
                if result:
                    data = xmltodict.parse(result)
                else:
                    data = None
            elif response.status == 595:
                _LOGGER.info("Status 595 returned, treating as timeout")
                raise BluesoundPlayer._TimeoutException()
            else:
                _LOGGER.error("Error %s on %s", response.status, url)
                return None

        except (asyncio.TimeoutError, aiohttp.ClientError):
            if raise_timeout:
                _LOGGER.info("Timeout: %s", self.host)
                raise
            _LOGGER.debug("Failed communicating: %s", self.host)
            return None

        return data