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


Python aiohttp.ContentTypeError方法代码示例

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


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

示例1: get_launch_dict

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def get_launch_dict(launch_number: int = 0) -> Dict:
    """Get a launch information dictionary for the given launch.

    If launch_number <= 0 (the default), get the "next" launch.
    """

    route = launch_number if launch_number > 0 else "next"
    spacex_api_url = f"https://api.spacexdata.com/v3/launches/{route}"

    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(spacex_api_url) as response:
                if response.status != 200:
                    logging.error(f"Response status: {response.status}")
                    return {}
                return await response.json()

    except aiohttp.client_exceptions.ClientConnectorError:
        logging.error("Cannot connect to api.spacexdata.com")
        return {}

    except aiohttp.ContentTypeError:
        logging.error("JSON decode failed")
        return {} 
开发者ID:r-spacex,项目名称:SpaceXLaunchBot,代码行数:26,代码来源:spacex.py

示例2: _fetch_token

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def _fetch_token(self, claim: str):
        """
        Requests a short-term token from the DDB Auth Service given a Discord user claim in JWT form.

        :param str claim: The JWT representing the Discord user.
        :returns: A tuple representing the short-term token for the user and its TTL, or (None, None).
        :rtype: tuple[str or None,int or None]
        """
        body = {"Token": claim}
        try:
            async with self.http.post(AUTH_DISCORD, json=body) as resp:
                if not 199 < resp.status < 300:
                    raise AuthException(f"Auth Service returned {resp.status}: {await resp.text()}")
                try:
                    data = await resp.json()
                except (aiohttp.ContentTypeError, ValueError, TypeError):
                    raise AuthException(f"Could not deserialize Auth Service response: {await resp.text()}")
        except aiohttp.ServerTimeoutError:
            raise AuthException("Timed out connecting to Auth Service")
        return data['token'], data.get('ttl') 
开发者ID:avrae,项目名称:avrae,代码行数:22,代码来源:ddb.py

示例3: fetch

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def fetch(url, pass_through=False):
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers={"accept": 'application/activity+json',
                                             "user-agent": f"PubGate v:{__version__}"}
                               ) as resp:
            status_code = resp.status
            logger.info(f"Fetch {url}, status: {resp.status}, {resp.reason}")

            try:
                result = await resp.json(encoding='utf-8')
                failed = False
            except aiohttp.ContentTypeError as e:
                result = {'fetch_error': await resp.text()}
                status_code = 500
                failed = e

            if pass_through:
                return status_code, result
            elif failed:
                raise failed
            return result 
开发者ID:autogestion,项目名称:pubgate,代码行数:23,代码来源:networking.py

示例4: cmd_dog

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def cmd_dog(self, ctx: command.Context) -> str:
        input_text = ctx.input

        status, text = await util.tg.get_text_input(ctx, input_text)
        if not status:
            if isinstance(text, str):
                return text

            return "__Unknown error.__"

        await ctx.respond("Uploading text to [Dogbin](https://del.dog/)...")

        async with self.bot.http.post("https://del.dog/documents", data=text) as resp:
            try:
                resp_data = await resp.json()
            except aiohttp.ContentTypeError:
                return "__Dogbin is currently experiencing issues. Try again later.__"

            return f'https://del.dog/{resp_data["key"]}' 
开发者ID:kdrag0n,项目名称:pyrobud,代码行数:21,代码来源:network.py

示例5: maybe_raise_for_status

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def maybe_raise_for_status(self, response: aiohttp.ClientResponse, should_raise: bool) -> None:
        """Raise ResponseCodeError for non-OK response if an exception should be raised."""
        if should_raise and response.status >= 400:
            try:
                response_json = await response.json()
                raise ResponseCodeError(response=response, response_json=response_json)
            except aiohttp.ContentTypeError:
                response_text = await response.text()
                raise ResponseCodeError(response=response, response_text=response_text) 
开发者ID:python-discord,项目名称:bot,代码行数:11,代码来源:api.py

示例6: from_critterdb

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def from_critterdb(cls, ctx, url, published=True):
        log.info(f"Getting bestiary ID {url}...")
        api_base = "https://critterdb.com:443/api/publishedbestiaries" if published \
            else "https://critterdb.com:443/api/bestiaries"
        sha256_hash = hashlib.sha256()
        sha256_hash.update(BESTIARY_SCHEMA_VERSION)
        async with aiohttp.ClientSession() as session:
            if published:
                creatures = await get_published_bestiary_creatures(url, session, api_base, sha256_hash)
            else:
                creatures = await get_link_shared_bestiary_creatures(url, session, api_base, sha256_hash)

            async with session.get(f"{api_base}/{url}") as resp:
                try:
                    raw = await resp.json()
                except (ValueError, aiohttp.ContentTypeError):
                    raise ExternalImportError("Error importing bestiary metadata. Are you sure the link is right?")
                name = raw['name']
                desc = raw['description']
                sha256_hash.update(name.encode() + desc.encode())

        # try and find a bestiary by looking up upstream|hash
        # if it exists, return it
        # otherwise commit a new one to the db and return that
        sha256 = sha256_hash.hexdigest()
        log.debug(f"Bestiary hash: {sha256}")
        existing_bestiary = await ctx.bot.mdb.bestiaries.find_one({"upstream": url, "sha256": sha256})
        if existing_bestiary:
            log.info("This bestiary already exists, subscribing")
            existing_bestiary = Bestiary.from_dict(existing_bestiary)
            await existing_bestiary.subscribe(ctx)
            return existing_bestiary

        parsed_creatures = [_monster_factory(c, name) for c in creatures]
        b = cls(None, sha256, url, published, name, parsed_creatures, desc)
        await b.write_to_db(ctx)
        await b.subscribe(ctx)
        return b 
开发者ID:avrae,项目名称:avrae,代码行数:40,代码来源:bestiary.py

示例7: parse_critterdb_response

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def parse_critterdb_response(resp, sha256_hash):
    try:
        raw_creatures = await resp.json()
        sha256_hash.update(await resp.read())
    except (ValueError, aiohttp.ContentTypeError):
        raise ExternalImportError("Error importing bestiary: bad data. Are you sure the link is right?")
    return raw_creatures


# critterdb -> bestiary helpers 
开发者ID:avrae,项目名称:avrae,代码行数:12,代码来源:bestiary.py

示例8: _request

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def _request(self, *, http_verb, api_url, req_args):
        """Submit the HTTP request with the running session or a new session.
        Returns:
            A dictionary of the response data.
        """
        session = None
        use_running_session = self.session and not self.session.closed
        if use_running_session:
            session = self.session
        else:
            session = aiohttp.ClientSession(
                timeout=aiohttp.ClientTimeout(total=self.timeout),
                auth=req_args.pop("auth", None),
            )

        response = None
        try:
            async with session.request(http_verb, api_url, **req_args) as res:
                data = {}
                try:
                    data = await res.json()
                except aiohttp.ContentTypeError:
                    self._logger.debug(
                        f"No response data returned from the following API call: {api_url}."
                    )
                response = {
                    "data": data,
                    "headers": res.headers,
                    "status_code": res.status,
                }
        finally:
            if not use_running_session:
                await session.close()
        return response

    # =================================================================
    # urllib based WebClient
    # ================================================================= 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:40,代码来源:base_client.py

示例9: handle_exception

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [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

示例10: get_data

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def get_data(self, url):
        """Base data retrieval method."""
        async with self.session.get(url) as r:
            try:
                data = await r.json()
            except aiohttp.ContentTypeError:
                await asyncio.sleep(1)
                try:
                    data = await r.json()
                except aiohttp.ContentTypeError:
                    return None
        return data 
开发者ID:shibdib,项目名称:Firetail,代码行数:14,代码来源:esi.py

示例11: refresh_access_token

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def refresh_access_token(self, refresh_token, auth):
        header = {'Authorization': 'Basic {}'.format(auth)}
        params = {'grant_type': 'refresh_token',
                  'refresh_token': refresh_token}

        sess = self.session
        async with sess.get(OAUTH_URL, params=params, headers=header) as r:
            try:
                data = await r.json()
            except aiohttp.ContentTypeError:
                return None
            return data 
开发者ID:shibdib,项目名称:Firetail,代码行数:14,代码来源:esi.py

示例12: verify_token

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def verify_token(self, access_token):
        header = {'Authorization': 'Bearer {}'.format(access_token)}

        async with self.session.get(OAUTH_URL, headers=header) as r:
            try:
                data = await r.json()
            except aiohttp.ContentTypeError:
                return None
            return data

    # Token Restricted 
开发者ID:shibdib,项目名称:Firetail,代码行数:13,代码来源:esi.py

示例13: handle_exception

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [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 as error:
        raise UnknownBackendResponse(error.message)
    except aiohttp.ClientResponseError as error:
        if error.status == HTTPStatus.UNAUTHORIZED:
            raise AuthenticationRequired(error.message)
        if error.status == HTTPStatus.FORBIDDEN:
            raise AccessDenied(error.message)
        if error.status == HTTPStatus.SERVICE_UNAVAILABLE:
            raise BackendNotAvailable(error.message)
        if error.status == HTTPStatus.TOO_MANY_REQUESTS:
            raise TooManyRequests(error.message)
        if error.status >= 500:
            raise BackendError(error.message)
        if error.status >= 400:
            logger.warning(
                "Got status %d while performing %s request for %s",
                error.status, error.request_info.method, str(error.request_info.url)
            )
            raise UnknownError(error.message)
    except aiohttp.ClientError as e:
        logger.exception("Caught exception while performing request")
        raise UnknownError(repr(e)) 
开发者ID:gogcom,项目名称:galaxy-integrations-python-api,代码行数:37,代码来源:http.py

示例14: _post_request

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def _post_request(self, url, data, timeout=10):
        async with aiohttp.ClientSession() as client:
            async with client.request('POST',
                                      url=url,
                                      timeout=timeout,
                                      json=data,
                                      headers={'Content-Type': 'application/json; charset=utf-8'}) as response:
                try:
                    await response.json()
                    return response
                except aiohttp.ContentTypeError as ex:
                    error = await response.text()
                    raise ValueError(error) 
开发者ID:CoinAlpha,项目名称:hummingbot,代码行数:15,代码来源:zero_ex_coordinator_v3.py

示例15: fetch_nekos_life

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ContentTypeError [as 别名]
def fetch_nekos_life(self, ctx, rp_action):

        async with aiohttp.ClientSession() as session:
            async with session.get(f"https://api.nekos.dev/api/v3/images/sfw/gif/{rp_action}/?count=20") as resp:
                try:
                    content = await resp.json(content_type=None)
                except (ValueError, aiohttp.ContentTypeError) as ex:
                    log.debug("Pruned by exception, error below:")
                    log.debug(ex)
                    return []

        if content["data"]["status"]["code"] == 200:
            return content["data"]["response"]["urls"] 
开发者ID:Jintaku,项目名称:Jintaku-Cogs-V3,代码行数:15,代码来源:roleplay.py


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