How to use the requests.exceptions.ConnectionError function in requests

To help you get started, we’ve selected a few requests examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PaloAltoNetworks / autofocus-client-library / tests / mocks.py View on Github external
def conn_error(url, request):
    raise requests.exceptions.ConnectionError()
github dephell / dephell / dephell / controllers / _repos.py View on Github external
def _has_api(url: str) -> bool:
    if urlparse(url).hostname in ('pypi.org', 'python.org', 'test.pypi.org'):
        return True
    full_url = urljoin(url, 'dephell/json/')
    try:
        response = requests.head(full_url)
    except (SSLError, ConnectionError):
        return False
    return response.status_code < 400
github chrismattmann / tika-python / tika.py View on Github external
def startServer(tikaServerJar, cmd=StartServerCmd):
    cmd = cmd % tikaServerJar
    try: 
        echo2('Executing: %s' %cmd)
        p = os.system(cmd)
        time.sleep(5)
    except requests.exceptions.ConnectionError as e:
        p.kill()
github asdaraujo / edge2ai-workshop / setup / terraform / resources / cdsw_setup.py View on Github external
try:
            r = s.post(CDSW_API + '/users', json={
                    'email': EMAIL,
                    'name': FULL_NAME,
                    'username': USERNAME,
                    'password': PASSWORD,
                    'type': 'user'
                }, timeout=10)
            if r.status_code == 201:
                break
            elif r.status_code == 422:
                print('WARNING: User admin already exists')
                break
        except requests.exceptions.ConnectTimeout:
            pass
        except requests.exceptions.ConnectionError:
            pass
        if r:
            print('Waiting for CDSW to be ready... (error code: %s)' % (r.status_code,))
        else:
            print('Waiting for CDSW to be ready... (connection timed out)')
        time.sleep(10)

    print('# Authenticate')
    r = s.post(CDSW_API + '/authenticate', json={'login': USERNAME, 'password': PASSWORD})
    s.headers.update({'Authorization': 'Bearer ' + r.json()['auth_token']})
    
    print('# Check if model is already running')
    r = s.post(CDSW_ALTUS_API + '/models/list-models', json={'projectOwnerName': 'admin', 'latestModelDeployment': True, 'latestModelBuild': True})
    models = [m for m in r.json() if m['name'] == 'IoT Prediction Model']
    if models and models[0]['latestModelDeployment']['status'] == 'deployed':
        print('Model is already deployed!! Skipping.')
github inspirehep / inspire / bibtasklets / bst_scoap3_importer.py View on Github external
def bst_scoap3_importer():
    """Import from SCOAP3."""
    try:
        request = requests.get('http://repo.scoap3.org/ffts_for_inspire.py/csv', timeout=60)
    except (HTTPError, ConnectionError, Timeout):
        register_exception()
        return
    task_sleep_now_if_required(can_stop_too=True)

    fd_update, name_update = mkstemp(
        suffix='.xml',
        prefix='bibupload_scoap3_',
        dir=CFG_TMPSHAREDDIR
    )

    out_update = fdopen(fd_update, 'w')
    fd_new, name_new = mkstemp(
        suffix='.xml',
        prefix='bibupload_scoap3_',
        dir=CFG_TMPSHAREDDIR
    )
github msalvaris / gpu_monitor / gpumon / influxdb / gpu_logger.py View on Github external
database: Name of database to log data to. It will create the database if one doesn't exist
    port: A number indicating the port on which influxdb is listening
    series_name: Name of series/table to log data to
    polling_interval: polling interval for measurements in seconds [default:1]
    retention_duration: the duration to retain the measurements for valid values are 1h, 90m, 12h, 7d, and 4w. default:1d
    tags: One or more tags to apply to the data. These can then be used to group or select timeseries
          Example: --machine my_machine --cluster kerb01

    """

    logger = _logger()
    logger.info('Trying to connect to {} on port {} as {}'.format(ip_or_url, port, username))
    try:
        client = InfluxDBClient(ip_or_url, port, username, password)
        response = client.ping()
    except ConnectionError:
        logger.warning('Could not connect to InfluxDB. GPU metrics NOT being recorded')
        raise MetricsRecordingFailed()

    logger.info('Connected | version {}'.format(response))
    _switch_to_database(client, database)

    logger.info('Measurement retention duration {}'.format(retention_duration))
    _set_retention_policy(client, database, retention_duration)

    to_db = compose(_create_influxdb_writer(client, tags=tags),
                    _gpu_to_influxdb_format(series_name))
    logger.info('Starting logging...')
    return start_pushing_measurements_to(to_db, polling_interval=polling_interval)
github erudit / eruditorg / eruditorg / erudit / fedora / modelmixins.py View on Github external
def get_erudit_object(self):
        """
        Returns the liberuditarticle's object associated with the considered Django object.
        """
        fedora_xml_content_key = 'fedora-object-{pid}'.format(pid=self.pid)
        fedora_xml_content = cache.get(fedora_xml_content_key, None)

        try:
            assert fedora_xml_content is None
            fedora_xml_content = self.fedora_object.xml_content
        except (RequestFailed, ConnectionError):  # pragma: no cover
            if settings.DEBUG:
                # In DEBUG mode RequestFailed or ConnectionError errors can occur
                # really often because the dataset provided by the Fedora repository
                # is not complete.
                return
            raise
        except AssertionError:
            # We've fetched the XML content from the cache so we just pass
            pass
        else:
            # Stores the XML content of the object for further use
            cache.set(
                fedora_xml_content_key, fedora_xml_content, self.fedora_xml_content_cache_timeout)

        return self.erudit_class(fedora_xml_content) if fedora_xml_content else None
github nicolas-carolo / hsploit / searcher / vulnerabilities / exploits / windows_x86 / dos / 44500.py View on Github external
def main():
    try:
        if len(sys.argv) <= 3 and len (sys.argv) >= 2:
            try:
                url = sanitize_url(sys.argv[1])
                print(' [#] LOADING!')
                if (check_server(url) != 404):
                    send_jewish_payload(url)
                else:
                    print(' [!] Server shutdown or not found')
            except requests.exceptions.ConnectionError:
                print(' [~] BOOOOOM! PRTG Server has been exploded!')
            except requests.exceptions.InvalidURL:
                print(' [!] Invalid URL')
            except requests.exceptions.Timeout:
                print(' [!] Connection Timeout\n')
        else:
            print('Example usage: ./'+sys.argv[0]+' http://192.168.0.10/index.htm')
    except KeyboardInterrupt:
        print(' [!] Jewish Napalm Canceled;.....[./]')
if __name__ == '__main__':