本文整理汇总了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 {}
示例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')
示例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
示例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"]}'
示例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)
示例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
示例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
示例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
# =================================================================
示例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()
示例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
示例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
示例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
示例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))
示例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)
示例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"]