Python aiohttp.client_exceptions.ContentTypeError() Examples
The following are 10
code examples of aiohttp.client_exceptions.ContentTypeError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
aiohttp.client_exceptions
, or try the search function
.
Example #1
Source File: http.py From mautrix-python with Mozilla Public License 2.0 | 6 votes |
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()
Example #2
Source File: dns.py From yui with GNU Affero General Public License v3.0 | 5 votes |
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, )
Example #3
Source File: daemon.py From pantalaimon with Apache License 2.0 | 5 votes |
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(), )
Example #4
Source File: daemon.py From pantalaimon with Apache License 2.0 | 5 votes |
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))
Example #5
Source File: exchange_rate_manager.py From lbry-sdk with MIT License | 5 votes |
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
Example #6
Source File: endpoints.py From rasa-for-botfront with Apache License 2.0 | 5 votes |
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
Example #7
Source File: bot.py From yui with GNU Affero General Public License v3.0 | 4 votes |
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) )
Example #8
Source File: daemon.py From pantalaimon with Apache License 2.0 | 4 votes |
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
Example #9
Source File: daemon.py From pantalaimon with Apache License 2.0 | 4 votes |
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(), )
Example #10
Source File: daemon.py From pantalaimon with Apache License 2.0 | 4 votes |
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(), )