當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。