当前位置: 首页>>代码示例>>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;未经允许,请勿转载。