當前位置: 首頁>>代碼示例>>Python>>正文


Python exceptions.ConnectionError方法代碼示例

本文整理匯總了Python中requests.exceptions.ConnectionError方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.ConnectionError方法的具體用法?Python exceptions.ConnectionError怎麽用?Python exceptions.ConnectionError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在requests.exceptions的用法示例。


在下文中一共展示了exceptions.ConnectionError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: send

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def send(current_user=None):
    """
    CASSH add
    """
    pubkey = request.files['file']
    username = request.form['username']
    payload = {}
    payload.update({'realname': current_user['name'], 'password': current_user['password']})
    payload.update({'username': username})
    payload.update({'pubkey': pubkey.read().decode('UTF-8')})
    try:
        req = put(APP.config['CASSH_URL'] + '/client', \
                data=payload, \
                headers=APP.config['HEADERS'], \
                verify=False)
    except ConnectionError:
        return Response('Connection error : %s' % APP.config['CASSH_URL'])
    if 'Error' in req.text:
        return Response(req.text)
    return redirect('/status') 
開發者ID:nbeguier,項目名稱:cassh,代碼行數:22,代碼來源:cassh_web.py

示例2: test_download_timeout

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def test_download_timeout(self):
        a = auth.Authorize(scope, token_file, secrets_file)
        a.authorize()
        retry_error = False
        start = datetime.now()

        try:
            _ = a.session.get("https://httpbin.org//delay/5", stream=True, timeout=0.2)
        except exc.ConnectionError as e:
            retry_error = True
            print(e)

        elapsed = datetime.now() - start
        self.assertEqual(retry_error, True)
        # .2 timeout by 5 retries = 1 sec
        self.assertGreater(elapsed.seconds, 1) 
開發者ID:gilesknap,項目名稱:gphotos-sync,代碼行數:18,代碼來源:test_units.py

示例3: get_pod_relay_preferences

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def get_pod_relay_preferences(self, host):
        """Query remote pods on https first, fall back to http."""
        logging.info("Querying %s" % host)
        try:
            try:
                response = requests.get("https://%s/.well-known/x-social-relay" % host,
                                timeout=5,
                                headers={"User-Agent": config.USER_AGENT})
            except timeout:
                response = None
            if not response or response.status_code != 200:
                response = requests.get("http://%s/.well-known/x-social-relay" % host,
                                timeout=5,
                                headers={"User-Agent": config.USER_AGENT})
                if response.status_code != 200:
                    return None
        except (ConnectionError, Timeout, timeout):
            return None
        try:
            # Make sure we have a valid x-social-relay doc
            validate(response.json(), self.schema)
            return response.text
        except (ValueError, ValidationError):
            return None 
開發者ID:jaywink,項目名稱:social-relay,代碼行數:26,代碼來源:poll_pods.py

示例4: from_exc

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def from_exc(cls, exc: Exception) -> "InternalError":
        exception_type = f"{exc.__class__.__module__}.{exc.__class__.__qualname__}"
        if isinstance(exc, HTTPError):
            if exc.response.status_code == 404:
                message = f"Schema was not found at {exc.url}"
            else:
                message = f"Failed to load schema, code {exc.response.status_code} was returned from {exc.url}"
            return cls(message=message, exception_type=exception_type)
        exception = format_exception(exc)
        exception_with_traceback = format_exception(exc, include_traceback=True)
        if isinstance(exc, exceptions.ConnectionError):
            message = f"Failed to load schema from {exc.request.url}"
        else:
            message = "An internal error happened during a test run"
        return cls(
            message=message,
            exception_type=exception_type,
            exception=exception,
            exception_with_traceback=exception_with_traceback,
        ) 
開發者ID:kiwicom,項目名稱:schemathesis,代碼行數:22,代碼來源:events.py

示例5: test_verify_tools_download_failure

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def test_verify_tools_download_failure(build_command):
    "If the build tools can't be retrieved, the build fails"
    build_command.build_app = mock.MagicMock()
    build_command.download_url = mock.MagicMock(
        side_effect=requests_exceptions.ConnectionError
    )

    # Try to invoke the build
    with pytest.raises(BriefcaseCommandError):
        build_command()

    # The download was attempted
    build_command.download_url.assert_called_with(
        url='https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-wonky.AppImage',
        download_path=build_command.dot_briefcase_path / 'tools'
    )

    # But it failed, so the file won't be made executable...
    assert build_command.os.chmod.call_count == 0

    # and the command won't retain the downloaded filename.
    assert build_command.linuxdeploy_appimage != 'new-downloaded-file'

    # and no build will be attempted
    assert build_command.build_app.call_count == 0 
開發者ID:beeware,項目名稱:briefcase,代碼行數:27,代碼來源:test_build.py

示例6: test_jdk_download_failure

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def test_jdk_download_failure(test_command, tmp_path):
    "If an error occurs downloading the JDK, an error is raised"
    # Mock Linux as the host
    test_command.host_os = 'Linux'

    # Mock a failure on download
    test_command.download_url.side_effect = requests_exceptions.ConnectionError

    # Invoking verify_jdk causes a network failure.
    with pytest.raises(NetworkFailure):
        verify_jdk(command=test_command)

    # That download was attempted
    test_command.download_url.assert_called_with(
        url="https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/download/"
            "jdk8u242-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u242b08.tar.gz",
        download_path=tmp_path / "tools",
    )
    # No attempt was made to unpack the archive
    assert test_command.shutil.unpack_archive.call_count == 0 
開發者ID:beeware,項目名稱:briefcase,代碼行數:22,代碼來源:test_verify_jdk.py

示例7: test

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def test(self):
        patience = 100
        while True:
            try:
                response = requests.get("http://localhost:{}".format(self.port))
                break
            except ConnectionError:
                patience -= 1
                if not patience:
                    self.fail(
                        "Couldn't get response from app, (Python executable {})".format(
                            sys.executable
                        )
                    )
                else:
                    sleep(0.1)

        self.assertIsInstance(response, Response)
        self.assertIn("Hello There!", response.text) 
開發者ID:johnbywater,項目名稱:eventsourcing,代碼行數:21,代碼來源:test_flask.py

示例8: get_302

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def get_302(url, headers=None, encoding='UTF-8'):
    """GET請求發送包裝"""
    try:
        html = requests.get(url, headers=headers, proxies=proxies, timeout=_tiemout, allow_redirects=False)
        status_code = html.status_code
        if status_code == 302:
            html = html.headers.get("Location", "")
        elif status_code == 200:
            html = html.content.decode(encoding)
            html = html.replace('\x00', '').strip()
        else:
            html = ""
        return html
    except ConnectionError as e:
        return "ERROR:" + "HTTP連接錯誤"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP連接超時錯誤"
    except Exception as e:
        return 'ERROR:' + str(e) 
開發者ID:HatBoy,項目名稱:Struts2-Scan,代碼行數:21,代碼來源:Struts2Scan.py

示例9: get_stream

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def get_stream(url, headers=None, encoding='UTF-8'):
    """分塊接受數據"""
    try:
        lines = requests.get(url, headers=headers, timeout=_tiemout, stream=True, proxies=proxies)
        html = list()
        for line in lines.iter_lines():
            if b'\x00' in line:
                break
            line = line.decode(encoding)
            html.append(line.strip())
        return '\r\n'.join(html).strip()
    except ChunkedEncodingError as e:
        return '\r\n'.join(html).strip()
    except ConnectionError as e:
        return "ERROR:" + "HTTP連接錯誤"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP連接超時錯誤"
    except Exception as e:
        return 'ERROR:' + str(e) 
開發者ID:HatBoy,項目名稱:Struts2-Scan,代碼行數:21,代碼來源:Struts2Scan.py

示例10: post_stream

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def post_stream(url, data=None, headers=None, encoding='UTF-8', files=None):
    """分塊接受數據"""
    try:
        lines = requests.post(url, data=data, headers=headers, timeout=_tiemout, stream=True, proxies=proxies,
                              files=None)
        html = list()
        for line in lines.iter_lines():
            line = line.decode(encoding)
            html.append(line.strip())
        return '\r\n'.join(html).strip()
    except ChunkedEncodingError as e:
        return '\r\n'.join(html).strip()
    except ConnectionError as e:
        return "ERROR:" + "HTTP連接錯誤"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP連接超時錯誤"
    except Exception as e:
        return 'ERROR:' + str(e) 
開發者ID:HatBoy,項目名稱:Struts2-Scan,代碼行數:20,代碼來源:Struts2Scan.py

示例11: requests_get

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def requests_get(url, **kwargs):
    USER_AGENTS = (
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
        'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0',
        'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
        ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) '
         'Chrome/19.0.1084.46 Safari/536.5'),
        ('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46'
         'Safari/536.5')
    )
    try:
        r = requests.get(
            url,
            timeout=12,
            headers={'User-Agent': random.choice(USER_AGENTS)}, **kwargs
        )
    except ConnectionError:
        exit_after_echo('Network connection failed.')
    except Timeout:
        exit_after_echo('timeout.')
    return r 
開發者ID:protream,項目名稱:iquery,代碼行數:23,代碼來源:utils.py

示例12: get_tenant_list

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def get_tenant_list(self, filter_dict={}):
        '''Obtain tenants of VIM
        filter_dict can contain the following keys:
            name: filter by tenant name
            id: filter by tenant uuid/id
            <other VIM specific>
        Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
        '''
        self.logger.debug("Getting tenant from VIM filter: '%s'", str(filter_dict))
        try:
            self._reload_connection()
            tenant_class_list=self.keystone.tenants.findall(**filter_dict)
            tenant_list=[]
            for tenant in tenant_class_list:
                tenant_list.append(tenant.to_dict())
            return tenant_list
        except (ksExceptions.ConnectionError, ksExceptions.ClientException)  as e:
            self._format_exception(e) 
開發者ID:nfvlabs,項目名稱:openmano,代碼行數:20,代碼來源:vimconn_openstack.py

示例13: new_user

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def new_user(self, user_name, user_passwd, tenant_id=None):
        '''Adds a new user to openstack VIM'''
        '''Returns the user identifier'''
        self.logger.debug("osconnector: Adding a new user to VIM")
        try:
            self._reload_connection()
            user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
            #self.keystone.tenants.add_user(self.k_creds["username"], #role)
            return user.id
        except ksExceptions.ConnectionError as e:
            error_value=-vimconn.HTTP_Bad_Request
            error_text= type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0]))
        except ksExceptions.ClientException as e: #TODO remove
            error_value=-vimconn.HTTP_Bad_Request
            error_text= type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0]))
        #TODO insert exception vimconn.HTTP_Unauthorized
        #if reaching here is because an exception
        if self.debug:
            self.logger.debug("new_user " + error_text)
        return error_value, error_text 
開發者ID:nfvlabs,項目名稱:openmano,代碼行數:22,代碼來源:vimconn_openstack.py

示例14: __get_auth_token

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def __get_auth_token(self):
        request_data = '{"username":"%s","password":"%s"}' % (self.username, self.password)
        for connection_url in self.urls:
            try:
                response = self.session.post('%s/_open/auth' % connection_url, data=request_data)
                if response.ok:
                    json_data = response.content
                    if json_data:
                        data_dict = json_mod.loads(json_data.decode("utf-8"))
                        return data_dict.get('jwt')
            except requests_exceptions.ConnectionError:
                if connection_url is not self.urls[-1]:
                    logging.critical("Unable to connect to %s trying another", connection_url)
                else:
                    logging.critical("Unable to connect to any of the urls: %s", self.urls)
                    raise 
開發者ID:ArangoDB-Community,項目名稱:pyArango,代碼行數:18,代碼來源:jwauth.py

示例15: test_is_remote_video_enabled_non_grid_extras

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import ConnectionError [as 別名]
def test_is_remote_video_enabled_non_grid_extras(req_get_mock, utils):
    # Configure mock
    req_get_mock.side_effect = ConnectionError('exception error')

    # Get remote video configuration and check result
    assert utils.is_remote_video_enabled('10.20.30.40') is False 
開發者ID:Telefonica,項目名稱:toolium,代碼行數:8,代碼來源:test_driver_utils.py


注:本文中的requests.exceptions.ConnectionError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。