本文整理匯總了Python中aiohttp.client_exceptions.ContentTypeError方法的典型用法代碼示例。如果您正苦於以下問題:Python client_exceptions.ContentTypeError方法的具體用法?Python client_exceptions.ContentTypeError怎麽用?Python client_exceptions.ContentTypeError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類aiohttp.client_exceptions
的用法示例。
在下文中一共展示了client_exceptions.ContentTypeError方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _send
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def _send(self, method: Method, endpoint: str, content: Union[bytes, str],
query_params: Dict[str, str], headers: Dict[str, str]) -> JSON:
while True:
request = self.session.request(str(method), endpoint, data=content,
params=query_params, headers=headers)
async with request as response:
if response.status < 200 or response.status >= 300:
errcode = message = None
try:
response_data = await response.json()
errcode = response_data["errcode"]
message = response_data["error"]
except (JSONDecodeError, ContentTypeError, KeyError):
pass
raise make_request_error(http_status=response.status,
text=await response.text(),
errcode=errcode, message=message)
if response.status == 429:
resp = await response.json()
await asyncio.sleep(resp["retry_after_ms"] / 1000, loop=self.loop)
else:
return await response.json()
示例2: query
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def query(domain: str, server: DNSServer) -> Result:
url = 'http://checkdnskr.appspot.com/api/lookup?{}'.format(
urlencode({'domain': domain, 'ip': server.ip})
)
async with aiohttp.ClientSession() as session:
async with session.get(url) as res:
async with res:
if res.status == 200:
try:
data = await res.json(loads=json.loads)
data['error'] = False
except ContentTypeError:
data = {
'A': '',
'error': True,
}
return Result(
server_name=server.name,
server_ip=server.ip,
a_record=data['A'],
error=data['error'],
)
return Result(
server_name=server.name,
server_ip=server.ip,
a_record='',
error=False,
)
示例3: messages
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def messages(self, request):
access_token = self.get_access_token(request)
if not access_token:
return self._missing_token
client = await self._find_client(access_token)
if not client:
return self._unknown_token
try:
response = await self.forward_request(request)
except ClientConnectionError as e:
return web.Response(status=500, text=str(e))
if response.status == 200:
try:
json_response = await response.json()
json_response = await self.decrypt_body(
client, json_response, sync=False
)
return web.json_response(
json_response, headers=CORS_HEADERS, status=response.status
)
except (JSONDecodeError, ContentTypeError):
pass
return web.Response(
status=response.status,
content_type=response.content_type,
headers=CORS_HEADERS,
body=await response.read(),
)
示例4: filter
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def filter(self, request):
access_token = self.get_access_token(request)
if not access_token:
return self._missing_token
try:
content = await request.json()
except (JSONDecodeError, ContentTypeError):
return self._not_json
sanitized_content = self.sanitize_filter(content)
return await self.forward_to_web(request, data=json.dumps(sanitized_content))
示例5: get_response
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def get_response(self):
async with aiohttp_request('get', self.url, params=self.params, timeout=self.request_timeout) as response:
try:
self._last_response = await response.json()
except ContentTypeError as e:
self._last_response = {}
log.warning("Could not parse exchange rate response from %s: %s", self.name, e.message)
log.debug(await response.text())
return self._last_response
示例6: request
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def request(
self,
method: Text = "post",
subpath: Optional[Text] = None,
content_type: Optional[Text] = "application/json",
**kwargs: Any,
) -> Optional[Any]:
"""Send a HTTP request to the endpoint. Return json response, if available.
All additional arguments will get passed through
to aiohttp's `session.request`."""
# create the appropriate headers
headers = {}
if content_type:
headers["Content-Type"] = content_type
if "headers" in kwargs:
headers.update(kwargs["headers"])
del kwargs["headers"]
url = concat_url(self.url, subpath)
async with self.session() as session:
async with session.request(
method,
url,
headers=headers,
params=self.combine_parameters(kwargs),
**kwargs,
) as response:
if response.status >= 400:
raise ClientResponseError(
response.status, response.reason, await response.content.read()
)
try:
return await response.json()
except ContentTypeError:
return None
示例7: call
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def call(
self,
method: str,
data: Dict[str, Any] = None,
*,
token: str = None,
json_mode: bool = False,
) -> APIResponse:
"""Call API methods."""
async with aiohttp.ClientSession() as session:
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload: Union[str, aiohttp.FormData]
if json_mode:
payload = json.dumps(data)
headers['Content-Type'] = 'application/json'
headers['Authorization'] = 'Bearer {}'.format(
token or self.config.TOKEN
)
else:
payload = aiohttp.FormData(data or {})
payload.add_field('token', token or self.config.TOKEN)
try:
async with session.post(
'https://slack.com/api/{}'.format(method),
data=payload,
headers=headers,
) as response:
try:
result = await response.json(loads=json.loads)
except ContentTypeError:
result = await response.text()
return APIResponse(
body=result,
status=response.status,
headers=response.headers,
)
except ClientConnectorError:
raise APICallError(
'fail to call {} with {}'.format(method, data)
)
示例8: _find_client
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def _find_client(self, access_token):
client_info = self.client_info.get(access_token, None)
if not client_info:
async with aiohttp.ClientSession() as session:
try:
method, path = Api.whoami(access_token)
resp = await session.request(
method,
self.homeserver_url + path,
proxy=self.proxy,
ssl=self.ssl,
)
except ClientConnectionError:
return None
if resp.status != 200:
return None
try:
body = await resp.json()
except (JSONDecodeError, ContentTypeError):
return None
try:
user_id = body["user_id"]
except KeyError:
return None
if user_id not in self.pan_clients:
logger.warn(
f"User {user_id} doesn't have a matching pan " f"client."
)
return None
logger.info(
f"Homeserver confirmed valid access token "
f"for user {user_id}, caching info."
)
client_info = ClientInfo(user_id, access_token)
self.client_info[access_token] = client_info
client = self.pan_clients.get(client_info.user_id, None)
return client
示例9: login
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def login(self, request):
try:
body = await request.json()
except (JSONDecodeError, ContentTypeError):
# After a long debugging session the culprit ended up being aiohttp
# and a similar bug to
# https://github.com/aio-libs/aiohttp/issues/2277 but in the server
# part of aiohttp. The bug is fixed in the latest master of
# aiohttp.
# Return 500 here for now since quaternion doesn't work otherwise.
# After aiohttp 4.0 gets replace this with a 400 M_NOT_JSON
# response.
return web.json_response(
{
"errcode": "M_NOT_JSON",
"error": "Request did not contain valid JSON.",
},
status=500,
)
user = self._get_login_user(body)
password = body.get("password", "")
logger.info(f"New user logging in: {user}")
try:
response = await self.forward_request(request)
except ClientConnectionError as e:
return web.Response(status=500, text=str(e))
try:
json_response = await response.json()
except (JSONDecodeError, ContentTypeError):
json_response = None
if response.status == 200 and json_response:
user_id = json_response.get("user_id", None)
access_token = json_response.get("access_token", None)
if user_id and access_token:
logger.info(
f"User: {user} succesfully logged in, starting "
f"a background sync client."
)
await self.start_pan_client(access_token, user, user_id, password)
return web.Response(
status=response.status,
content_type=response.content_type,
headers=CORS_HEADERS,
body=await response.read(),
)
示例10: sync
# 需要導入模塊: from aiohttp import client_exceptions [as 別名]
# 或者: from aiohttp.client_exceptions import ContentTypeError [as 別名]
def sync(self, request):
access_token = self.get_access_token(request)
if not access_token:
return self._missing_token
client = await self._find_client(access_token)
if not client:
return self._unknown_token
sync_filter = request.query.get("filter", None)
query = CIMultiDict(request.query)
if sync_filter:
try:
sync_filter = json.loads(sync_filter)
except (JSONDecodeError, TypeError):
pass
if isinstance(sync_filter, dict):
sync_filter = json.dumps(self.sanitize_filter(sync_filter))
query["filter"] = sync_filter
try:
response = await self.forward_request(
request, params=query, token=client.access_token
)
except ClientConnectionError as e:
return web.Response(status=500, text=str(e))
if response.status == 200:
try:
json_response = await response.json()
json_response = await self.decrypt_body(client, json_response)
return web.json_response(
json_response, headers=CORS_HEADERS, status=response.status
)
except (JSONDecodeError, ContentTypeError):
pass
return web.Response(
status=response.status,
content_type=response.content_type,
headers=CORS_HEADERS,
body=await response.read(),
)