Python aiohttp.client_exceptions.ClientResponseError() Examples

The following are 8 code examples of aiohttp.client_exceptions.ClientResponseError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.client_exceptions , or try the search function .
Example #1
Source File: test_http_client.py    From asgard-api with MIT License 6 votes vote down vote up
def test_exceptions_have_detail_info_about_the_request_that_failed(
        self
    ):
        """
        Cada exceção lançada deve carregar algumas infos sobre o request original.
        A ClientResponseError da aiohttp tem tudo que queremos.

        A exception lançada pelo client contém:
          - request_info original
          - status (int)
        """
        client = HttpClient()
        url = "https://httpbin.org/status/404"

        try:
            await client.get(url)
        except HTTPNotFound as e:
            self.assertEqual(HTTPStatus.NOT_FOUND, e.status)
            self.assertEqual(url, str(e.request_info.url))
            self.assertEqual("GET", e.request_info.method)
            self.assertIsNotNone(e.request_info.headers) 
Example #2
Source File: wallabag.py    From wallabag_api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle_json_response(responses):
        """
        get the json data response
        :param responses: the json response
        :return the json data without 'root' node
        """
        json_data = {}
        if responses.status != 200:
            err_msg = HttpProcessingError(code=responses.status,
                                          message=await responses.json())
            logging.error("Wallabag: aiohttp error {err_msg}".format(
                err_msg=err_msg))
        else:
            try:
                json_data = responses.json()
            except ClientResponseError as e:
                # sometimes json_data does not return any json() without
                # any error. This is due to the grabbing URL which "rejects"
                # the URL
                logging.error("Wallabag: aiohttp error {code} {message}"
                              .format(code=e.code, message=e.message))
        return await json_data 
Example #3
Source File: aiohttp.py    From hass-nabucasa with GNU General Public License v3.0 5 votes vote down vote up
def raise_for_status(self):
        """Raise error if status is 400 or higher."""
        if self.status >= 400:
            raise ClientResponseError(
                None, None, code=self.status, headers=self.headers
            ) 
Example #4
Source File: client.py    From asgard-api with MIT License 5 votes vote down vote up
def _request(
        self,
        method: str,
        url: str,
        headers: Dict[str, str] = {},
        timeout: ClientTimeout = None,
        raise_for_status: bool = True,
        **kwargs: Dict[str, Any],
    ) -> ClientResponse:
        """
        Método que é usado por todos os outros métodos para fazer um request.
        O parametros recebidos por esse métodos definem os parametros recebidos pelo client de uma forma geral.
        """
        try:
            resp = await self._session.request(
                method,
                url,
                headers=headers,
                timeout=timeout,
                raise_for_status=raise_for_status,
                allow_redirects=True,
                **kwargs,
            )
        except ClientResponseError as ce:
            if ce.status == HTTPStatus.NOT_FOUND:
                raise HTTPNotFound(request_info=ce.request_info)
            if ce.status == HTTPStatus.INTERNAL_SERVER_ERROR:
                raise HTTPInternalServerError(request_info=ce.request_info)
            if ce.status == HTTPStatus.BAD_REQUEST:
                raise HTTPBadRequest(request_info=ce.request_info)
            raise ce

        return resp 
Example #5
Source File: test_http_client.py    From asgard-api with MIT License 5 votes vote down vote up
def test_re_raise_original_exception(self):
        """
        Se o request lançar uma exception que não estamos tratando, devemos re-lançar.
        """
        client = HttpClient()
        url = "https://httpbin.org/status/415"

        try:
            await client.get(url)
        except ClientResponseError as e:
            self.assertEqual(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, e.status)
            self.assertEqual(url, str(e.request_info.url))
            self.assertEqual("GET", e.request_info.method)
            self.assertIsNotNone(e.request_info.headers) 
Example #6
Source File: client.py    From aiomoex with The Unlicense 5 votes vote down vote up
def get(self, start=None):
        """Загрузка данных

        :param start:
            Номер элемента с которого нужно загрузить данные. Используется для дозагрузки данных, состоящих из
            нескольких блоков. При отсутствии данные загружаются с начального элемента

        :return:
            Блок данных с отброшенной вспомогательной информацией - словарь, каждый ключ которого
            соответствует одной из таблиц с данными. Таблицы являются списками словарей, которые напрямую конвертируются
            в pandas.DataFrame
        """
        if not self.is_session_closed():
            session = self._client_session
        else:
            raise ISSMoexError("Откройте сессию для работы с MOEX ISS")
        url = self._url
        query = self._make_query(start)
        async with session.get(url, params=query) as respond:
            try:
                respond.raise_for_status()
            except client_exceptions.ClientResponseError:
                raise ISSMoexError("Неверный url", respond.url)
            else:
                data = await respond.json()
                return data[1] 
Example #7
Source File: aiohttp.py    From gql with MIT License 4 votes vote down vote up
def execute(
        self,
        document: DocumentNode,
        variable_values: Optional[Dict[str, str]] = None,
        operation_name: Optional[str] = None,
        extra_args: Dict[str, Any] = {},
    ) -> ExecutionResult:
        """Execute the provided document AST against the configured remote server.
        This uses the aiohttp library to perform a HTTP POST request asynchronously
        to the remote server.

        The result is sent as an ExecutionResult object.
        """

        query_str = print_ast(document)
        payload: Dict[str, Any] = {
            "query": query_str,
        }

        if variable_values:
            payload["variables"] = variable_values
        if operation_name:
            payload["operationName"] = operation_name

        post_args = {
            "json": payload,
        }

        # Pass post_args to aiohttp post method
        post_args.update(extra_args)

        if self.session is None:
            raise TransportClosed("Transport is not connected")

        async with self.session.post(self.url, ssl=self.ssl, **post_args) as resp:
            try:
                result = await resp.json()
            except Exception:
                # We raise a TransportServerError if the status code is 400 or higher
                # We raise a TransportProtocolError in the other cases

                try:
                    # Raise a ClientResponseError if response status is 400 or higher
                    resp.raise_for_status()

                except ClientResponseError as e:
                    raise TransportServerError from e

                raise TransportProtocolError("Server did not return a GraphQL result")

            if "errors" not in result and "data" not in result:
                raise TransportProtocolError("Server did not return a GraphQL result")

            return ExecutionResult(errors=result.get("errors"), data=result.get("data")) 
Example #8
Source File: twitter.py    From cjworkbench with GNU Affero General Public License v3.0 4 votes vote down vote up
def fetch(params, *, secrets, get_stored_dataframe):
    querytype = QueryType(params["querytype"])
    query: str = params[querytype.query_param_name]
    credentials = (secrets.get("twitter_credentials") or {}).get("secret")

    if not query.strip() and not credentials:
        return None  # Don't create a version

    if not query.strip():
        return "Please enter a query"

    if not credentials:
        return "Please sign in to Twitter"

    try:
        if params["accumulate"]:
            old_tweets = await get_stored_tweets(get_stored_dataframe)
            tweets = await get_new_tweets(credentials, querytype, query, old_tweets)
            tweets = merge_tweets(old_tweets, tweets)
        else:
            tweets = await get_new_tweets(credentials, querytype, query, None)
        return tweets

    except ValueError as err:
        return str(err)

    except ClientResponseError as err:
        if err.status:
            if querytype == QueryType.USER_TIMELINE and err.status == 401:
                return "User %s's tweets are private" % query
            elif querytype == QueryType.USER_TIMELINE and err.status == 404:
                return "User %s does not exist" % query
            elif err.status == 429:
                return (
                    "Twitter API rate limit exceeded. "
                    "Please wait a few minutes and try again."
                )
            else:
                return "Error from Twitter: %d %s" % (err.status, err.message)
        else:
            return "Error fetching tweets: %s" % str(err)

    except ClientError as err:
        return "Error fetching tweets: %s" % str(err)