requests.exceptions.RequestException

Here are the examples of the python api requests.exceptions.RequestException taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

429 Examples 7

3 Source : graph.py
with GNU General Public License v3.0
from 2martin2

    def __init__(self, url: str) -> None:
        """
        - May raise requests.RequestException if there is a problem connecting to the subgraph"""
        transport = RequestsHTTPTransport(url=url)
        try:
            self.client = Client(transport=transport, fetch_schema_from_transport=True)
        except (requests.exceptions.RequestException) as e:
            raise RemoteError(f'Failed to connect to the graph at {url} due to {str(e)}') from e

    def query(

3 Source : device.py
with MIT License
from alexmohr

    def _register_without_auth(self, registration_action):
        try:
            self._send_http(
                registration_action.url,
                method=HttpMethod.GET,
                raise_errors=True)
            # set the pin to something to make sure init_device is called
            self.pin = 9999
        except requests.exceptions.RequestException:
            return AuthenticationResult.ERROR
        else:
            return AuthenticationResult.SUCCESS

    @staticmethod

3 Source : device.py
with MIT License
from alexmohr

    def _register_v3(self, registration_action):
        try:
            self._send_http(registration_action.url,
                            method=HttpMethod.GET, raise_errors=True)
        except requests.exceptions.RequestException as ex:
            return self._handle_register_error(ex)
        else:
            return AuthenticationResult.SUCCESS

    def _register_v4(self, registration_action):

3 Source : test_connection.py
with MIT License
from ArkEcosystem

def test_connection_raises_for_request_retry_failure():
    responses.add(
        responses.GET,
        'http://127.0.0.1:4003/spongebob',
        body=requests.exceptions.RequestException())

    connection = Connection('http://127.0.0.1:4003')

    with pytest.raises(ArkHTTPException) as exception:
        connection.get('spongebob')

    assert len(responses.calls) == 3


def test_handle_response_raises_for_no_content_in_response():

3 Source : test_pypokedex.py
with MIT License
from arnavb

def test_requests_errors(responses):
    responses.add(
        responses.GET,
        "https://pokeapi.co/api/v2/pokemon/sample",
        body=requests.exceptions.RequestException("Some error"),
    )

    with pytest.raises(PyPokedexError):
        pypokedex.get(name="sample")


def test_description_http_errors(responses):

3 Source : dpnk_tags.py
with GNU General Public License v3.0
from auto-mat

def cyklistesobe(city_slug, order="created_at"):
    api = slumber.API(
        "http://www.cyklistesobe.cz/api/", session=TimeoutRequestsSession()
    )
    kwargs = {}
    if city_slug:
        kwargs["group"] = city_slug
    try:
        cyklistesobe = api.issues.get(order=order, per_page=5, page=0, **kwargs)
    except (
        slumber.exceptions.SlumberBaseException,
        requests.exceptions.RequestException,
    ):
        logger.exception("Error fetching cyklistesobe page")
        cyklistesobe = None
    return {"cyklistesobe": cyklistesobe}


@register.inclusion_tag("templatetags/wp_news.html")

3 Source : test_metrics_resource.py
with Apache License 2.0
from aws-solutions

def test_request_exception(mocker, test_event, caplog):
    requests_mock = mocker.MagicMock()
    mocker.patch(MOCKER_REQUESTS, requests_mock)
    requests_mock.exceptions.RequestException = requests.exceptions.RequestException
    requests_mock.post.side_effect = requests.exceptions.ConnectionError(
        "there was a connection error"
    )

    with caplog.at_level(logging.INFO):
        send_metrics(test_event, None)

    assert (
        "Could not send usage data: there was a connection error"
    ) in caplog.messages


def test_general_exception(mocker, test_event, caplog):

3 Source : test_metrics_resource.py
with Apache License 2.0
from aws-solutions

def test_general_exception(mocker, test_event, caplog):
    requests_mock = mocker.MagicMock()
    mocker.patch(MOCKER_REQUESTS, requests_mock)
    requests_mock.exceptions.RequestException = requests.exceptions.RequestException
    requests_mock.post.side_effect = ValueError("general exception")

    with caplog.at_level(logging.INFO):
        send_metrics(test_event, None)

    assert (
        "Unknown error when trying to send usage data: general exception"
    ) in caplog.messages

3 Source : test_sanity.py
with MIT License
from bakdata

def test_initial_registration():
    @retrying.retry(
        stop_max_delay=MAX_TIMEOUT,
        wait_fixed=1 * 1000,
        retry_on_exception=lambda e: isinstance(
            e, requests.exceptions.RequestException
        ),
        retry_on_result=lambda r: len(r)   <   2,
    )
    def registered_workers() -> typing.List[str]:
        return _get_workers_within_cluster()

    assert set(registered_workers()) == set([WORKER_NAME + "-0", WORKER_NAME + "-1"])


@pytest.mark.incremental

3 Source : emsfp_firmware_base.py
with GNU General Public License v3.0
from cbcrc

    def clearSlot(self,slot):
        """[summary]
        Clear the firmware slot of Embrionix module.

        Return:
        A list containg the boolean result and message of the result [boolean result,message]       
        """
        try:
            data = {'clear_'+slot:'Clear'}
            response = self.session.post("http://" + self.ip + "/config/active_element_action", data=data)
            sleep(30)
            return [True, "The selected slot " + slot + " on the module " +  self.ip + " has been cleared."]
        except requestsExceptions.RequestException as e:
            return [False, "Error clearing slot " + slot + " on the module " +  self.ip + " : " + e]

    def uploadFirmware(self, slot, filePath):

3 Source : emsfp_firmware_base.py
with GNU General Public License v3.0
from cbcrc

    def setActiveSlot(self,slot):
        """[summary]
        Set selected slot as Active.
        Return: A list containg the boolean result and message of the result [boolean result,message]
        """
        data = {'warm_boot_'+slot:'Load Now'}
        try:
            post_response = self.session.post("http://" + self.ip + "/config/active_element_action", data=data )
            #Add a delay before next query
            sleep(5)
            if(post_response.status_code == 202):
                return [True,"The selected slot " + slot + " on the module " +  self.ip + " has been set as active. Response code : " + str(post_response.status_code)]
            return [False,"Error setting the selected slot " + slot + " on the module " +  self.ip + " as active. Response code: " + + str(post_response.status_code)]
        except requestsExceptions.RequestException as e:
            return [False,"Error communicating with the module " +  self.ip + ". Ensure that you can manually set the slot as active via the web interface.\n" + \
            f"Exception message: {e}"]

    def getActiveFirmawareVersion(self):

3 Source : test_dnacentersdk.py
with MIT License
from cisco-en-programmability

    def test_custom_base_url(self):
        custom_url = "https://custom.domain.com/v1/"
        with pytest.raises((dnacentersdk.exceptions.ApiError, requests.exceptions.RequestException)):
            dnacentersdk.DNACenterAPI(username=DNA_CENTER_USERNAME,
                                      password=DNA_CENTER_PASSWORD,
                                      encoded_auth=DNA_CENTER_ENCODED_AUTH,
                                      base_url=custom_url,
                                      verify=DEFAULT_VERIFY,
                                      version=DNA_CENTER_VERSION)

    @pytest.mark.dnacentersdk

3 Source : usage_automation.py
with Apache License 2.0
from cloudblue

    def _get_usage_template_download_location(self, product_id):
        # type: (str) -> str
        try:
            response, _ = self._api.get(url='{}usage/products/{}/template/'
                                        .format(self.config.api_url, product_id))
            response_dict = json.loads(response)
            return response_dict['template_link']
        except (requests.exceptions.RequestException, KeyError, TypeError, ValueError):
            return ''

    @staticmethod

3 Source : client.py
with Apache License 2.0
from coinbase

    def _handle_request_error(self, e):
        if isinstance(e, requests.exceptions.RequestException):
            msg = "Unexpected error communicating with Coinbase Commerce."
            err = "{}: {}".format(type(e).__name__, str(e))
        else:
            msg = ("Unexpected error communicating with Coinbase Commerce. "
                   "It looks like there's probably a configuration "
                   "issue locally.")
            err = "A {} was raised".format(type(e).__name__)
            if str(e):
                err += " with error message {}".format(str(e))
            else:
                err += " with no error message"
        msg = textwrap.fill(msg) + "\n\n(Network error: {})".format(err)
        raise APIError(msg)

    def get(self, *args, **kwargs):

3 Source : mlflow.py
with Apache License 2.0
from criteo

def optional_mlflow(return_default=None):
    def optional_mlflow_decorator(f):
        @wraps(f)
        def wrapper(*args, **kwds):
            if use_mlflow():
                try:
                    return f(*args, **kwds)
                except (ConnectionError, requests_exc.RequestException, exceptions.MlflowException):
                    logger.exception("mlflow connection error")
            else:
                return return_default
        return wrapper
    return optional_mlflow_decorator


@optional_mlflow(return_default="")

3 Source : scraper.py
with GNU General Public License v3.0
from cyberaz0r

def get_req(url, attempts=0):
	if attempts == 3:
		print_error('Request for "{}" failed three times in a row, skipping...'.format(url))
		return ''
	
	try:
		r = sess.get(url)
	except requests.exceptions.RequestException:
		print_warning('Request for "{}" failed, retrying in 5 secs...'.format(url))
		sleep(5)
		return get_req(url, attempts + 1)
	
	return r.text


# parse Moodle links from an HTML page
def scrape(parent_url):

3 Source : test_download_authenticator_metadata.py
with GNU General Public License v3.0
from CZ-NIC

    def test_error_response(self):
        with responses.RequestsMock() as rsps:
            with self.assertRaisesMessage(CommandError, 'MDS response error.'):
                rsps.add(responses.GET, 'https://mds2.fidoalliance.org/', body=RequestException('Some error'))
                _get_metadata()

    def test_malformed_response(self):

3 Source : stability.py
with Apache License 2.0
from ErikGartner

def tryd(func, *args, **kwargs):
    """
    Tries a Docker call that might fail due to underlying issues in the
    connectetion to the Daemon. After repeated failures the error is propagated.
    """
    return retry(
        func,
        cfg["STABILITY"]["RETRY"]["RETRIES"],
        cfg["STABILITY"]["RETRY"]["SLEEP_TIME"],
        (requests.exceptions.RequestException,),
        *args,
        **kwargs
    )


def trym(func, *args, **kwargs):

3 Source : test_experiment.py
with Apache License 2.0
from ErikGartner

    def test_docker_daemon_down(self):
        """
        ensure that starting experiment without Docker daemon fails
        correctly
        """
        down_docker = docker.DockerClient(base_url="tcp://127.0.0.1:9999")
        self.experiment._docker_client = down_docker

        with self.assertRaises(requests.exceptions.RequestException):
            self.experiment.start()
        self.assertFalse(self.experiment.is_running(), "Should not start.")
        self.assertEqual(
            self.experiment.get_result()["state"], "fail", "Should have failed."
        )

    def test_cancel_experiment(self):

3 Source : NodeosConnect.py
with MIT License
from EvaCoop

    def get(self, path, **kwargs):
        """
        A GET Http method.

        :param path: str: path to  api endpoint
        :param kwargs: json: arguments auth, headers, data ..etc.

        :return: response object

        """
        try:
            return self.session.get(self.base_url + path, verify=self.ssl_verify, **kwargs)
        except requests.exceptions.RequestException as e:
            raise e

    def post(self, path, **kwargs):

3 Source : NodeosConnect.py
with MIT License
from EvaCoop

    def post(self, path, **kwargs):
        """
        A POST Http method.

        :param path: str: path to  api endpoint
        :param kwargs: json: arguments auth, headers, data ..etc.

        :return: response object

        """
        try:
            return self.session.post(self.base_url + path, verify=self.ssl_verify, **kwargs)
        except requests.exceptions.RequestException as e:
            raise e

    @staticmethod

3 Source : update.py
with GNU General Public License v3.0
from FlashpointProject

    def worker(reporter, root_path, server, current, target):
        if target not in server.available_indexes():
            print('Could not find index: %s' % target)
            reporter.stop()
            return
        if target not in server.available_updates():
            print('Target version not available as an update')
            reporter.stop()
            return
        remote_root = server.get_root(target)
        try:
            current, target = server.fetch(current, reporter), server.fetch(target, reporter)
        except requests.exceptions.RequestException as e:
            print('Could not retrieve index: %s' % str(e))
            reporter.stop()
            return
        perform_update(root_path, current, target, remote_root, reporter)

    current, target = args.update

3 Source : crash_reporter.py
with MIT License
from garlicoin-project

    def send_report(self):
        try:
            response = BaseCrashReporter.send_report(self, "/crash.json").json()
        except requests.exceptions.RequestException:
            self.show_popup(_('Unable to send report'), _("Please check your network connection."))
        else:
            self.show_popup(_('Report sent'), response["text"])
            if response["location"]:
                self.open_url(response["location"])
        self.dismiss()

    def open_url(self, url):

3 Source : thread.py
with GNU General Public License v3.0
from guohuadeng

    def _handle_request(self, kwargs):
        try:
            response = self._session.request(**kwargs)
        except exc.RequestException as e:
            self._exceptions.put((kwargs, e))
        else:
            self._responses.put((kwargs, response))
        finally:
            self._jobs.task_done()

    def _make_request(self):

3 Source : xboxone.py
with MIT License
from hunterjm

    def _get_device_info(self):
        try:
            response = self.get('/device/  <  liveid>').json()
            if not response.get('success'):
                _LOGGER.debug('Console {0} not available'.format(self.liveid))
                return None
        except requests.exceptions.RequestException:
            _LOGGER.error('Unreachable device info / < liveid> endpoint')
            return None
        except Exception as e:
            _LOGGER.error('Unknown Error: %s', e)
            return None

        return response['device']

    def _update_console_status(self):

3 Source : xboxone.py
with MIT License
from hunterjm

    def _update_console_status(self):
        try:
            response = self.get('/device/  <  liveid>/console_status').json()
            if not response.get('success'):
                _LOGGER.error('Console {0} not available'.format(self.liveid))
                return None
        except requests.exceptions.RequestException:
            _LOGGER.error('Unreachable /console_status endpoint')
            return None
        except Exception as e:
            _LOGGER.error('Unknown Error: %s', e)
            return None

        self._console_status = response['console_status']

    def _update_media_status(self):

3 Source : xboxone.py
with MIT License
from hunterjm

    def _update_media_status(self):
        try:
            response = self.get('/device/  <  liveid>/media_status').json()
            if not response.get('success'):
                _LOGGER.error('Console {0} not available'.format(self.liveid))
                return None
        except requests.exceptions.RequestException:
            _LOGGER.error('Unreachable /media_status endpoint')
            return None
        except Exception as e:
            _LOGGER.error('Unknown Error: %s', e)
            return None

        self._media_status = response['media_status']

    def _update_volume_controls(self):

3 Source : xboxone.py
with MIT License
from hunterjm

    def _update_volume_controls(self):
        if self._volume_controls:
            return

        try:
            response = self.get('/device/  <  liveid>/ir').json()
            if not response.get('success'):
                _LOGGER.error('Console {0} not available'.format(self.liveid))
                return None
        except requests.exceptions.RequestException:
            _LOGGER.error('Unreachable /ir endpoint')
            return None
        except Exception as e:
            _LOGGER.error('Unknown Error: %s', e)
            return None

        self._volume_controls = response

    def poweron(self):

3 Source : xboxone.py
with MIT License
from hunterjm

    def poweron(self):
        try:
            url = '/device/  <  liveid>/poweron'
            params = None
            if self._ip:
                params = { 'addr': self._ip }
            response = self.get(url, params=params).json()
            if not response.get('success'):
                _LOGGER.error('Failed to poweron {0}'.format(self.liveid))
                return None
        except requests.exceptions.RequestException:
            _LOGGER.error('Unreachable /poweron endpoint')
            return None

        return response

    def poweroff(self):

3 Source : xboxone.py
with MIT License
from hunterjm

    def poweroff(self):
        try:
            response = self.get('/device/  <  liveid>/poweroff').json()
            if not response.get('success'):
                _LOGGER.error('Failed to poweroff {0}'.format(self.liveid))
                return None
        except requests.exceptions.RequestException:
            _LOGGER.error('Failed to call poweroff for {0}'.format(self.liveid))
            return None

        return response

    def ir_command(self, device, command):

3 Source : xboxone.py
with MIT License
from hunterjm

    def launch_title(self, launch_uri):
        try:
            apps = self.all_apps
            if launch_uri in apps.keys():
                launch_uri = apps[launch_uri]
            response = self.get('/device/  <  liveid>/launch/{0}'.format(launch_uri)).json()
            if not response.get('success'):
                return None
        except requests.exceptions.RequestException:
            _LOGGER.error('Failed to launch title \'{0}\' for {1}'.format(launch_uri, self.liveid))
            return None
        except Exception as e:
            _LOGGER.error('Unknown Error: %s', e)
            return None

        return response

    def _check_server(self):

3 Source : xboxone.py
with MIT License
from hunterjm

    def _check_server(self):
        if not self.is_server_correct_version:
            return False

        try:
            resp = self.get('/versions').json()
            version = resp['versions']['xbox-smartglass-rest']
            if version != REQUIRED_SERVER_VERSION:
                self.is_server_correct_version = False
                _LOGGER.error("Invalid xbox-smartglass-rest version: %s. Required: %s",
                              version, REQUIRED_SERVER_VERSION)
        except requests.exceptions.RequestException:
            self.is_server_up = False
            return False

        self.is_server_up = True
        return True

    def refresh(self):

3 Source : test_source.py
with Apache License 2.0
from ICTU

    def test_url_http_error(self, mock_get, request):
        """Test that the error is reported if a request exception occurs, while checking connection of a url."""
        mock_get.side_effect = requests.exceptions.RequestException
        request.json = dict(url=self.url)
        response = post_source_parameter(SOURCE_ID, "url", self.database)
        self.assert_url_check(response, -1, "RequestException")
        self.database.reports.insert_one.assert_called_once_with(self.report)
        updated_report = self.database.reports.insert_one.call_args[0][0]
        url = self.url
        self.assert_delta(
            f"url of source 'Source' of metric 'Metric' of subject 'Subject' in report 'Report' from '' to '{url}'",
            report=updated_report,
        )

    @patch.object(requests, "get")

3 Source : tests_meetecho.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools

    def test_request_helper_exception(self):
        self.requests_mock.register_uri(requests_mock.ANY, urljoin(API_BASE, 'exception/url/endpoint'), exc=requests.exceptions.RequestException)
        api = MeetechoAPI(API_BASE, CLIENT_ID, CLIENT_SECRET)
        for method in ['POST', 'GET']:
            with self.assertRaises(Exception) as context:
                api._request(method, 'exception/url/endpoint')
            self.assertIsInstance(context.exception, MeetechoAPIError)

    def test_time_serialization(self):

3 Source : journals.py
with MIT License
from iwasakishuto

    def is_request_successful(soup):
        """Check whether request is successful or not.
        
        Args:
            soup (BeautifulSoup) : A data structure representing a parsed HTML or XML document.        
        """
        if soup.get_text().startswith("Request unsuccessful"):
            raise RequestException(toRED("[403 Forbidden]\n") + soup.get_text() + toGREEN("\nPlease run Chrome with GUI browser."))
    
    def get_title_from_soup(self, soup):

3 Source : __init__.py
with MIT License
from jererobles

    def _get_uid(self):
        try:
            response = self.storage.session.get(url=Uhoo.URL_GET_UID)
            self._log_response(response)
            self.storage.session.headers.update(
                {Uhoo.UID_HEADER: response.json()["uId"]}
            )
        except requests.exceptions.RequestException as ex:
            print("HTTP Request failed: " + str(ex))

    def _get_client_code(self):

3 Source : __init__.py
with MIT License
from jererobles

    def _get_client_code(self):
        try:
            response = self.storage.session.post(
                url=Uhoo.URL_GET_CLIENT_CODE,
                data={
                    "clientId": Uhoo.CLIENT_ID,
                    "username": self.username,
                },
            )
            self._log_response(response)
            self.storage.session.headers.update(
                {Uhoo.CODE_HEADER: response.json()["code"]}
            )
        except requests.exceptions.RequestException as ex:
            print("HTTP Request failed: " + str(ex))

    def _renew_token(self):

3 Source : __init__.py
with MIT License
from jererobles

    def _get_data(self, retry=0):
        try:
            response = self.storage.session.get(url=Uhoo.URL_GET_DATA)
            self._log_response(response)
            if (
                response.status_code == 401 or response.status_code == 403
            ) and retry   <   2:
                self._renew_token()
                response = self._get_data(retry + 1)
            return response
        except requests.exceptions.RequestException as e:
            message = "HTTP Request failed: " + str(e)
            print(message)
            return message

    def get_data(self):

3 Source : __init__.py
with MIT License
from jererobles

    def logout(self):
        try:
            response = self.storage.session.get(url=Uhoo.URL_LOGOUT)
            self.storage.session.headers.pop()
            self._log_response(response)
        except requests.exceptions.RequestException as e:
            print("HTTP Request failed: " + str(e))

3 Source : egardia.py
with MIT License
from jest-community

    def alarm_disarm(self, code=None):
        """Send disarm command."""
        try:
            self._egardiasystem.alarm_disarm()
        except requests.exceptions.RequestException as err:
            _LOGGER.error("Egardia device exception occurred when "
                          "sending disarm command: %s", err)

    def alarm_arm_home(self, code=None):

3 Source : egardia.py
with MIT License
from jest-community

    def alarm_arm_home(self, code=None):
        """Send arm home command."""
        try:
            self._egardiasystem.alarm_arm_home()
        except requests.exceptions.RequestException as err:
            _LOGGER.error("Egardia device exception occurred when "
                          "sending arm home command: %s", err)

    def alarm_arm_away(self, code=None):

3 Source : egardia.py
with MIT License
from jest-community

    def alarm_arm_away(self, code=None):
        """Send arm away command."""
        try:
            self._egardiasystem.alarm_arm_away()
        except requests.exceptions.RequestException as err:
            _LOGGER.error("Egardia device exception occurred when "
                          "sending arm away command: %s", err)

3 Source : neurio_energy.py
with MIT License
from jest-community

    def get_active_power(self):
        """Return current power value."""
        try:
            sample = self.neurio_client.get_samples_live_last(self.sensor_id)
            self._active_power = sample['consumptionPower']
        except (requests.exceptions.RequestException, ValueError, KeyError):
            _LOGGER.warning("Could not update current power usage")
            return None

    def get_daily_usage(self):

3 Source : sensor.py
with MIT License
from jlamendo

    def activate_sock(self, dsn):
        try:
            r = self.api_post(
                "/dsns/%s/properties/APP_ACTIVE/datapoints.json" % dsn,
                {"datapoint": {"metadata": {}, "value": 1}},
            )
            r.raise_for_status()
            return True
        except requests.exceptions.RequestException as e:
            _LOGGER.error("Owlet Network error while activating Sock %s: %s" % (dsn, e))
            time.sleep(5)
            self.__client = requests.session()
            return False

    def sock_properties(self, dsn):

3 Source : defDiscord.py
with GNU General Public License v3.0
from Jxck-S

def sendDis(message, config, file_name = None, role_id = None):
    import requests
    from discord_webhook import DiscordWebhook
    if role_id != None:
        message += f"   <  @&{role_id}>"
    webhook = DiscordWebhook(url=config.get('DISCORD', 'URL'), content=message[0:1999], username=config.get('DISCORD', 'USERNAME'))
    if file_name != None:
        with open(file_name, "rb") as f:
            webhook.add_file(file=f.read(), filename=file_name)
    try:
        webhook.execute()
    except requests.exceptions.RequestException:
        pass

3 Source : google_query.py
with GNU General Public License v3.0
from KoalaV2

def get_source(url):

    try:
        session = HTMLSession()
        response = session.get(url)
        return response

    except requests.exceptions.RequestException as e:
        print(e)

def get_results(query):

3 Source : listeners.py
with MIT License
from kweimann

    def _send_message(self, message, **kwargs):
        try:
            response = requests.get(
                self._send_message_url,
                timeout=5,
                params={'chat_id': self.chat_id, 'text': message, **kwargs})
            response = response.json()
            if not response.get('ok'):
                logging.error(f'Failed to send telegram message: {response.get("description")}')
        except requests.exceptions.RequestException:
            logging.exception('Exception thrown while sending a telegram message.')
        except ValueError:
            logging.exception('Exception thrown while parsing the response.')

    @staticmethod

3 Source : http_client.py
with MIT License
from LanqingLi1993

    def _handle_request_error(self, e, method, url):
        if isinstance(e, requests.exceptions.RequestException):
            msg = ("Unexpected error communicating with OpenAI Gym "
                   "(while calling {} {}). "
                   "If this problem persists, let us know at "
                   "[email protected].".format(method, url))
            err = "%s: %s" % (type(e).__name__, str(e))
        else:
            msg = ("Unexpected error communicating with OpenAI Gym. "
                   "It looks like there's probably a configuration "
                   "issue locally.  If this problem persists, let us "
                   "know at [email protected].")
            err = "A %s was raised" % (type(e).__name__,)
            if str(e):
                err += " with error message %s" % (str(e),)
            else:
                err += " with no error message"
        msg = textwrap.fill(msg, width=140) + "\n\n(Network error: %s)" % (err,)
        raise error.APIConnectionError(msg)

3 Source : camera_manager.py
with MIT License
from maiermic

    def _ensure_connection(self):
        if self.camera:
            try:
                logger.debug(self.camera.get_state().__dict__)
                if not self.is_stream_started:
                    self._start_camera_stream()
            except (requests.exceptions.RequestException,
                    urllib3.exceptions.HTTPError):
                logger.debug('Lost connection to camera')
                self.is_stream_started = False
                self._connect()
        else:
            self._connect()

    def _connect(self):

3 Source : camera_manager.py
with MIT License
from maiermic

    def _start_camera_stream(self):
        try:
            self.camera.recmode()
            self.camera.start_stream()
            self.is_stream_started = True
            logger.debug('camera stream is started')
        except (requests.exceptions.RequestException,
                urllib3.exceptions.HTTPError,
                BusyError) as e:
            logger.error('Could not start camera stream: %s', e)

    def run(self):

See More Examples