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


Python client_exceptions.ClientResponseError方法代码示例

本文整理汇总了Python中aiohttp.client_exceptions.ClientResponseError方法的典型用法代码示例。如果您正苦于以下问题:Python client_exceptions.ClientResponseError方法的具体用法?Python client_exceptions.ClientResponseError怎么用?Python client_exceptions.ClientResponseError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在aiohttp.client_exceptions的用法示例。


在下文中一共展示了client_exceptions.ClientResponseError方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_exceptions_have_detail_info_about_the_request_that_failed

# 需要导入模块: from aiohttp import client_exceptions [as 别名]
# 或者: from aiohttp.client_exceptions import ClientResponseError [as 别名]
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) 
开发者ID:b2wdigital,项目名称:asgard-api,代码行数:23,代码来源:test_http_client.py

示例2: handle_json_response

# 需要导入模块: from aiohttp import client_exceptions [as 别名]
# 或者: from aiohttp.client_exceptions import ClientResponseError [as 别名]
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 
开发者ID:push-things,项目名称:wallabag_api,代码行数:24,代码来源:wallabag.py

示例3: raise_for_status

# 需要导入模块: from aiohttp import client_exceptions [as 别名]
# 或者: from aiohttp.client_exceptions import ClientResponseError [as 别名]
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
            ) 
开发者ID:NabuCasa,项目名称:hass-nabucasa,代码行数:8,代码来源:aiohttp.py

示例4: _request

# 需要导入模块: from aiohttp import client_exceptions [as 别名]
# 或者: from aiohttp.client_exceptions import ClientResponseError [as 别名]
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 
开发者ID:b2wdigital,项目名称:asgard-api,代码行数:35,代码来源:client.py

示例5: test_re_raise_original_exception

# 需要导入模块: from aiohttp import client_exceptions [as 别名]
# 或者: from aiohttp.client_exceptions import ClientResponseError [as 别名]
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) 
开发者ID:b2wdigital,项目名称:asgard-api,代码行数:16,代码来源:test_http_client.py

示例6: get

# 需要导入模块: from aiohttp import client_exceptions [as 别名]
# 或者: from aiohttp.client_exceptions import ClientResponseError [as 别名]
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] 
开发者ID:WLM1ke,项目名称:aiomoex,代码行数:28,代码来源:client.py

示例7: execute

# 需要导入模块: from aiohttp import client_exceptions [as 别名]
# 或者: from aiohttp.client_exceptions import ClientResponseError [as 别名]
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")) 
开发者ID:graphql-python,项目名称:gql,代码行数:56,代码来源:aiohttp.py

示例8: fetch

# 需要导入模块: from aiohttp import client_exceptions [as 别名]
# 或者: from aiohttp.client_exceptions import ClientResponseError [as 别名]
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) 
开发者ID:CJWorkbench,项目名称:cjworkbench,代码行数:46,代码来源:twitter.py


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