Python aiohttp.client_exceptions.ClientConnectorError() Examples

The following are 9 code examples of aiohttp.client_exceptions.ClientConnectorError(). 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: aiorpc.py    From ontology-python-sdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __post(self, payload):
        header = {'Content-type': 'application/json'}
        try:
            if self._session is None:
                async with ClientSession() as session:
                    async with session.post(self._url, json=payload, headers=header, timeout=10) as response:
                        res = json.loads(await response.content.read(-1))
            else:
                async with self._session.post(self._url, json=payload, headers=header, timeout=10) as response:
                    res = json.loads(await response.content.read(-1))
            if res['error'] != 0:
                if res['result'] != '':
                    raise SDKException(ErrorCode.other_error(res['result']))
                else:
                    raise SDKException(ErrorCode.other_error(res['desc']))
        except (asyncio.TimeoutError, client_exceptions.ClientConnectorError):
            raise SDKException(ErrorCode.connect_timeout(self._url)) from None
        return res 
Example #2
Source File: aiorestful.py    From ontology-python-sdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __post(self, url: str, data: str):
        try:
            if self.__session is None:
                async with ClientSession() as session:
                    async with session.post(url, data=data, timeout=10) as response:
                        res = json.loads(await response.content.read(-1))
            else:
                async with self.__session.post(url, data=data, timeout=10) as response:
                    res = json.loads(await response.content.read(-1))
            if res['Error'] != 0:
                if res['Result'] != '':
                    raise SDKException(ErrorCode.other_error(res['Result']))
                else:
                    raise SDKException(ErrorCode.other_error(res['Desc']))
            return res
        except (asyncio.TimeoutError, client_exceptions.ClientConnectorError):
            raise SDKException(ErrorCode.connect_timeout(self._url)) from None 
Example #3
Source File: aiorestful.py    From ontology-python-sdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __get(self, url):
        try:
            if self.__session is None:
                async with ClientSession() as session:

                    async with session.get(url, timeout=10) as response:
                        res = json.loads(await response.content.read(-1))
            else:
                async with self.__session.get(url, timeout=10) as response:
                    res = json.loads(await response.content.read(-1))
            if res['Error'] != 0:
                if res['Result'] != '':
                    raise SDKException(ErrorCode.other_error(res['Result']))
                else:
                    raise SDKException(ErrorCode.other_error(res['Desc']))
            return res
        except (asyncio.TimeoutError, client_exceptions.ClientConnectorError):
            raise SDKException(ErrorCode.connect_timeout(self._url)) from None 
Example #4
Source File: nowalletd.py    From nowallet with MIT License 6 votes vote down vote up
def initialize_wallet(self, _salt, _passphrase, bech32, rbf):
        try:
            server, port, proto = await nowallet.get_random_server(self.loop)
            connection = nowallet.Connection(self.loop, server, port, proto)
            self.wallet = nowallet.Wallet(
                _salt, _passphrase, connection, self.loop, self.chain)
            await connection.do_connect()
        except (SocksConnectionError, ClientConnectorError):
            self.print_json({
                "error": "Make sure Tor is installed and running before using nowalletd."
            })
            sys.exit(1)

        self.wallet.bech32 = bech32
        self.rbf = rbf

        await self.wallet.discover_all_keys()
        self.print_history()
        self.wallet.new_history = False 
Example #5
Source File: __init__.py    From target-stitch with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_send_exception():
    try:
        global SEND_EXCEPTION
        if SEND_EXCEPTION:
            raise SEND_EXCEPTION

    # An StitchClientResponseError means we received > 2xx response
    # Try to parse the "message" from the
    # json body of the response, since Stitch should include
    # the human-oriented message in that field. If there are
    # any errors parsing the message, just include the
    # stringified response.
    except StitchClientResponseError as exc:
        try:
            msg = "{}: {}".format(str(exc.status), exc.response_body)
        except: # pylint: disable=bare-except
            LOGGER.exception('Exception while processing error response')
            msg = '{}'.format(exc)
        raise TargetStitchException('Error persisting data to Stitch: ' +
                                    msg)

    # A ClientConnectorErrormeans we
    # couldn't even connect to stitch. The exception is likely
    # to be very long and gross. Log the full details but just
    # include the summary in the critical error message.
    except ClientConnectorError as exc:
        LOGGER.exception(exc)
        raise TargetStitchException('Error connecting to Stitch')

    except concurrent.futures._base.TimeoutError as exc: #pylint: disable=protected-access
        raise TargetStitchException("Timeout sending to Stitch") 
Example #6
Source File: zilliqa_api.py    From Zilliqa-Mining-Proxy with GNU General Public License v3.0 5 votes vote down vote up
def call(self, method, *params, **kwargs):
        if self.api_client is None:
            await self.init_client()

        try:
            return await self.api_client.request(
                method, *params,
                trim_log_values=True, **kwargs
            )
        except JsonRpcClientError as e:
            # fix for jsonrpcclient < 3.3.1
            if str(e) == INVALID_PARAMS:
                if len(params) == 1 and (isinstance(params[0], (dict, list))):
                    params = (list(params),)
                    return await self.api_client.request(
                        method, *params,
                        trim_log_values=True, **kwargs
                    )

            raise e
        except ClientConnectorError as e:
            logging.warning(f"Client connect exception captured, please check network or Zilliqa API server. Exception: {e}")
        except asyncio.CancelledError as e:
            logging.warning(f"Cancelled exception captured: {e}")
        except asyncio.TimeoutError as e:
            logging.warning("Timeout exception captured, please check network or Zilliqa API server")
        except:
            logging.warning(f"Unknown exception captured: {e}") 
Example #7
Source File: main.py    From nowallet with MIT License 5 votes vote down vote up
def do_login(self):
        email = self.root.ids.email_field.text
        passphrase = self.root.ids.pass_field.text
        confirm = self.root.ids.confirm_field.text
        if not email or not passphrase or not confirm:
            self.show_dialog("Error", "All fields are required.")
            return
        if passphrase != confirm:
            self.show_dialog("Error", "Passwords did not match.")
            return
        self.bech32 = self.root.ids.bech32_checkbox.active
        self.menu_items[0]["text"] = "View {}PUB".format(self.pub_char.upper())

        self.root.ids.sm.current = "wait"
        try:
            await self.do_login_tasks(email, passphrase)
        except (SocksConnectionError, ClientConnectorError):
            self.show_dialog("Error",
                             "Make sure Tor/Orbot is installed and running before using Nowallet.",
                             cb=lambda x: sys.exit(1))
            return
        self.update_screens()
        self.root.ids.sm.current = "main"
        await asyncio.gather(
            self.new_history_loop(),
            self.do_listen_task()
        ) 
Example #8
Source File: module_checker.py    From simplydomain with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fetch(self, sem, url, cname, session):
		async with sem:
			response_obj = {}
			response_obj['subdomain'] = "http://" + url
			response_obj['cname'] = cname
			response_obj['takeover'] = False
			for obj in PROVIDER_LIST:
				if all(key in cname for key in obj['cname']):
					try:
						async with session.get(response_obj['subdomain']) as response:
							print("Testing: {}".format(url))
							print("URL: {} Status: {}".format(response.url, response.status))
							data = await response.read()							
							for r in obj['response']:
								if r in str(data):
									response_obj['takeover'] = True
									response_obj['type'] = {}
									response_obj['type']['confidence'] = "HIGH"
									response_obj['type']['provider'] = obj['name']
									response_obj['type']['response'] = r
									response_obj['type']['response_status'] = response.status
									print("Got one: {}".format(response_obj))
									return response_obj
							return response_obj
					except ClientConnectorError as e:
						print("Connection Error: {} CNAME: {}".format(e,cname))
						response_obj['takeover'] = True
						response_obj['type'] = {}
						response_obj['type']['confidence'] = "MEDIUM"
						response_obj['type']['provider'] = obj['name']
						response_obj['type']['response'] = e
						response_obj['type']['response_status'] = None
						return response_obj
					except Exception as e:
						print("Doh!: {} ErrorType: {} CNAME: {}".format(e, type(e),cname))
			return None 
Example #9
Source File: bot.py    From yui with GNU Affero General Public License v3.0 4 votes vote down vote up
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)
                )