当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.ReadTimeout方法代码示例

本文整理汇总了Python中requests.exceptions.ReadTimeout方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ReadTimeout方法的具体用法?Python exceptions.ReadTimeout怎么用?Python exceptions.ReadTimeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在requests.exceptions的用法示例。


在下文中一共展示了exceptions.ReadTimeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: delete_user_from_group

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def delete_user_from_group(self,uname,gid):
        """
        将群用户从群中剔除,只有群管理员有权限
        """
        uid = ""
        for user in self.group_members[gid]:
            if user['NickName'] == uname:
                uid = user['UserName']
        if uid == "":
            return False
        url = self.base_uri + '/webwxupdatechatroom?fun=delmember&pass_ticket=%s' % self.pass_ticket
        params ={
            "DelMemberList": uid,
            "ChatRoomName": gid,
            "BaseRequest": self.base_request
        }
        headers = {'content-type': 'application/json; charset=UTF-8'}
        data = json.dumps(params, ensure_ascii=False).encode('utf8')
        try:
            r = self.session.post(url, data=data, headers=headers)
        except (ConnectionError, ReadTimeout):
            return False
        dic = r.json()
        return dic['BaseResponse']['Ret'] == 0 
开发者ID:moyuanz,项目名称:DevilYuan,代码行数:26,代码来源:wxbot.py

示例2: send_msg_by_uid

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def send_msg_by_uid(self, word, dst='filehelper'):
        url = self.base_uri + '/webwxsendmsg?pass_ticket=%s' % self.pass_ticket
        msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
        word = self.to_unicode(word)
        params = {
            'BaseRequest': self.base_request,
            'Msg': {
                "Type": 1,
                "Content": word,
                "FromUserName": self.my_account['UserName'],
                "ToUserName": dst,
                "LocalID": msg_id,
                "ClientMsgId": msg_id
            }
        }
        headers = {'content-type': 'application/json; charset=UTF-8'}
        data = json.dumps(params, ensure_ascii=False).encode('utf8')
        try:
            r = self.session.post(url, data=data, headers=headers)
        except (ConnectionError, ReadTimeout):
            return False
        dic = r.json()
        return dic['BaseResponse']['Ret'] == 0 
开发者ID:moyuanz,项目名称:DevilYuan,代码行数:25,代码来源:wxbot.py

示例3: handle_connection_errors

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def handle_connection_errors(client):
    try:
        yield
    except SSLError as e:
        log.error('SSL error: %s' % e)
        raise ConnectionError()
    except RequestsConnectionError as e:
        if e.args and isinstance(e.args[0], ReadTimeoutError):
            log_timeout_error(client.timeout)
            raise ConnectionError()
        exit_with_error(get_conn_error_message(client.base_url))
    except APIError as e:
        log_api_error(e, client.api_version)
        raise ConnectionError()
    except (ReadTimeout, socket.timeout):
        log_timeout_error(client.timeout)
        raise ConnectionError()
    except Exception as e:
        if is_windows():
            import pywintypes
            if isinstance(e, pywintypes.error):
                log_windows_pipe_error(e)
                raise ConnectionError()
        raise 
开发者ID:QData,项目名称:deepWordBug,代码行数:26,代码来源:errors.py

示例4: _docker_extract

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def _docker_extract(self, tag, package_path):
        container = self._docker.containers.run(image=tag, detach=True)
        exit_code = container.wait()["StatusCode"]
        logs = container.logs()
        LOG.debug("docker run logs: \n{}".format(logs.decode("utf-8").strip()))
        if exit_code != 0:
            raise TaskCatException("docker build failed")
        arc, _ = container.get_archive("/output/")
        with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
            for chunk in arc:
                tmpfile.write(chunk)
        with tarfile.open(tmpfile.name) as tar:
            for member in tar.getmembers():
                if member.name.startswith("output/"):
                    member.name = member.name[len("output/") :]
                    tar.extract(member)
            tar.extractall(path=str(package_path))
        try:
            container.remove()
        except ReadTimeout:
            LOG.warning(f"Could not remove container {container.id}")
        os.unlink(tmpfile.name)
        os.removedirs(str(package_path / "output")) 
开发者ID:aws-quickstart,项目名称:taskcat,代码行数:25,代码来源:_lambda_build.py

示例5: test_get_blockchain_events_adaptive_reduces_block_interval_after_timeout

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def test_get_blockchain_events_adaptive_reduces_block_interval_after_timeout(
    web3: Web3, token_network_registry_contract: Contract
):
    chain_state = BlockchainState(
        chain_id=ChainID(1),
        token_network_registry_address=to_canonical_address(
            token_network_registry_contract.address
        ),
        latest_committed_block=BlockNumber(4),
    )

    assert chain_state.current_event_filter_interval == DEFAULT_FILTER_INTERVAL

    with patch("raiden_libs.blockchain.get_blockchain_events", side_effect=ReadTimeout):
        _ = get_blockchain_events_adaptive(
            web3=web3,
            token_network_addresses=[],
            blockchain_state=chain_state,
            latest_confirmed_block=BlockNumber(1),
        )

        assert chain_state.current_event_filter_interval == DEFAULT_FILTER_INTERVAL // 5 
开发者ID:raiden-network,项目名称:raiden-services,代码行数:24,代码来源:test_blockchain.py

示例6: update_cookies

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def update_cookies(cookies=None):
    """
    更新或获取cookies
    :param cookies:
    :return:
    """
    if cookies is None:
        ctrl.COOKIES = requests.get(url=url_index.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT).cookies

    else:
        ctrl.COOKIES = cookies

    logger.info(ctrl.COOKIES)
    if len(ctrl.COOKIES) == 0:
        logger.error('cookie有问题')
        raise ReadTimeout('cookie有问题') 
开发者ID:will4906,项目名称:PatentCrawler,代码行数:18,代码来源:proxy.py

示例7: run_docker_container

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def run_docker_container(image: str, timeout: int = 300, command: Optional[str] = None, reraise: bool = False,
                         mount: Optional[Tuple[str, str]] = None, label: str = 'Docker', include_stderr: bool = True) -> str:
    container = None
    try:
        kwargs = {'mounts': [Mount(*mount, read_only=False, type='bind')]} if mount else {}
        client = docker.from_env()
        container = client.containers.run(image, command=command, network_disabled=True, detach=True, **kwargs)
        container.wait(timeout=timeout)
        return container.logs(stderr=include_stderr).decode()
    except ReadTimeout:
        logging.warning('[{}]: timeout while processing'.format(label))
        if reraise:
            raise
    except (DockerException, IOError):
        logging.warning('[{}]: encountered process error while processing'.format(label))
        if reraise:
            raise
    finally:
        if container:
            with suppress(DockerException):
                container.stop()
            container.remove() 
开发者ID:fkie-cad,项目名称:FACT_core,代码行数:24,代码来源:docker.py

示例8: get_docker_output

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def get_docker_output(arch_suffix: str, file_path: str, root_path: Path) -> dict:
    '''
    :return: in the case of no error, the output will have the form
    {
        'parameter 1': {'stdout': <b64_str>, 'stderr': <b64_str>, 'return_code': <int>},
        'parameter 2': {...},
        '...',
        'strace': {'stdout': <b64_str>, 'stderr': <b64_str>, 'return_code': <int>},
    }
    in case of an error, there will be an entry 'error' instead of the entries stdout/stderr/return_code
    '''
    command = '{arch_suffix} {target}'.format(arch_suffix=arch_suffix, target=file_path)
    try:
        return loads(run_docker_container(
            DOCKER_IMAGE, TIMEOUT_IN_SECONDS, command, reraise=True, mount=(CONTAINER_TARGET_PATH, str(root_path)),
            label='qemu_exec'
        ))
    except ReadTimeout:
        return {'error': 'timeout'}
    except (DockerException, IOError):
        return {'error': 'process error'}
    except JSONDecodeError:
        return {'error': 'could not decode result'} 
开发者ID:fkie-cad,项目名称:FACT_core,代码行数:25,代码来源:qemu_exec.py

示例9: process_object

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def process_object(self, file_object: FileObject):
        with TemporaryDirectory(prefix=self.NAME, dir=get_temp_dir_path(self.config)) as tmp_dir:
            file_path = Path(tmp_dir) / file_object.file_name
            file_path.write_bytes(file_object.binary)
            try:
                result = run_docker_container(
                    DOCKER_IMAGE, TIMEOUT_IN_SECONDS, CONTAINER_TARGET_PATH, reraise=True,
                    mount=(CONTAINER_TARGET_PATH, str(file_path)), label=self.NAME, include_stderr=False
                )
                file_object.processed_analysis[self.NAME] = loads(result)
            except ReadTimeout:
                file_object.processed_analysis[self.NAME]['warning'] = 'Analysis timed out. It might not be complete.'
            except (DockerException, IOError):
                file_object.processed_analysis[self.NAME]['warning'] = 'Analysis issues. It might not be complete.'
            except JSONDecodeError:
                logging.error('Could not decode JSON output: {}'.format(repr(result)))

            return file_object 
开发者ID:fkie-cad,项目名称:FACT_core,代码行数:20,代码来源:input_vectors.py

示例10: send

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
        try:
            ret = super().send(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
        except ConnectionError as error:
            if hasattr(error.args[0], "reason") and isinstance(error.args[0].reason, ReadTimeoutError):
                raise ReadTimeout(error.args[0], request=request)
            raise error
        else:
            return ret 
开发者ID:penetrate2hack,项目名称:ITWSV,代码行数:11,代码来源:crawler.py

示例11: apply_useradd_requests

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def apply_useradd_requests(self,RecommendInfo):
        url = self.base_uri + '/webwxverifyuser?r='+str(int(time.time()))+'&lang=zh_CN'
        params = {
            "BaseRequest": self.base_request,
            "Opcode": 3,
            "VerifyUserListSize": 1,
            "VerifyUserList": [
                {
                    "Value": RecommendInfo['UserName'],
                    "VerifyUserTicket": RecommendInfo['Ticket']             }
            ],
            "VerifyContent": "",
            "SceneListCount": 1,
            "SceneList": [
                33
            ],
            "skey": self.skey
        }
        headers = {'content-type': 'application/json; charset=UTF-8'}
        data = json.dumps(params, ensure_ascii=False).encode('utf8')
        try:
            r = self.session.post(url, data=data, headers=headers)
        except (ConnectionError, ReadTimeout):
            return False
        dic = r.json()
        return dic['BaseResponse']['Ret'] == 0 
开发者ID:moyuanz,项目名称:DevilYuan,代码行数:28,代码来源:wxbot.py

示例12: add_groupuser_to_friend_by_uid

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def add_groupuser_to_friend_by_uid(self,uid,VerifyContent):
        """
        主动向群内人员打招呼,提交添加好友请求
        uid-群内人员得uid   VerifyContent-好友招呼内容
        慎用此接口!封号后果自负!慎用此接口!封号后果自负!慎用此接口!封号后果自负!
        """
        if self.is_contact(uid):
            return True
        url = self.base_uri + '/webwxverifyuser?r='+str(int(time.time()))+'&lang=zh_CN'
        params ={
            "BaseRequest": self.base_request,
            "Opcode": 2,
            "VerifyUserListSize": 1,
            "VerifyUserList": [
                {
                    "Value": uid,
                    "VerifyUserTicket": ""
                }
            ],
            "VerifyContent": VerifyContent,
            "SceneListCount": 1,
            "SceneList": [
                33
            ],
            "skey": self.skey
        }
        headers = {'content-type': 'application/json; charset=UTF-8'}
        data = json.dumps(params, ensure_ascii=False).encode('utf8')
        try:
            r = self.session.post(url, data=data, headers=headers)
        except (ConnectionError, ReadTimeout):
            return False
        dic = r.json()
        return dic['BaseResponse']['Ret'] == 0 
开发者ID:moyuanz,项目名称:DevilYuan,代码行数:36,代码来源:wxbot.py

示例13: add_friend_to_group

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def add_friend_to_group(self,uid,group_name):
        """
        将好友加入到群聊中
        """
        gid = ''
        #通过群名获取群id,群没保存到通讯录中的话无法添加哦
        for group in self.group_list:
            if group['NickName'] == group_name:
                gid = group['UserName']
        if gid == '':
            return False
        #获取群成员数量并判断邀请方式
        group_num=len(self.group_members[gid])
        print ('[DEBUG] group_name:%s group_num:%s' % (group_name,group_num))
        #通过群id判断uid是否在群中
        for user in self.group_members[gid]:
            if user['UserName'] == uid:
                #已经在群里面了,不用加了
                return True
        if group_num<=100:
            url = self.base_uri + '/webwxupdatechatroom?fun=addmember&pass_ticket=%s' % self.pass_ticket
            params ={
                "AddMemberList": uid,
                "ChatRoomName": gid,
                "BaseRequest": self.base_request
            }
        else:
            url = self.base_uri + '/webwxupdatechatroom?fun=invitemember'
            params ={
                "InviteMemberList": uid,
                "ChatRoomName": gid,
                "BaseRequest": self.base_request
            }
        headers = {'content-type': 'application/json; charset=UTF-8'}
        data = json.dumps(params, ensure_ascii=False).encode('utf8')
        try:
            r = self.session.post(url, data=data, headers=headers)
        except (ConnectionError, ReadTimeout):
            return False
        dic = r.json()
        return dic['BaseResponse']['Ret'] == 0 
开发者ID:moyuanz,项目名称:DevilYuan,代码行数:43,代码来源:wxbot.py

示例14: invite_friend_to_group

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def invite_friend_to_group(self,uid,group_name):
        """
        将好友加入到群中。对人数多的群,需要调用此方法。
        拉人时,可以先尝试使用add_friend_to_group方法,当调用失败(Ret=1)时,再尝试调用此方法。
        """
        gid = ''
        # 通过群名获取群id,群没保存到通讯录中的话无法添加哦
        for group in self.group_list:
            if group['NickName'] == group_name:
                gid = group['UserName']
        if gid == '':
            return False
        # 通过群id判断uid是否在群中
        for user in self.group_members[gid]:
            if user['UserName'] == uid:
                # 已经在群里面了,不用加了
                return True
        url = self.base_uri + '/webwxupdatechatroom?fun=invitemember&pass_ticket=%s' % self.pass_ticket
        params = {
            "InviteMemberList": uid,
            "ChatRoomName": gid,
            "BaseRequest": self.base_request
        }
        headers = {'content-type': 'application/json; charset=UTF-8'}
        data = json.dumps(params, ensure_ascii=False).encode('utf8')
        try:
            r = self.session.post(url, data=data, headers=headers)
        except (ConnectionError, ReadTimeout):
            return False
        dic = r.json()
        return dic['BaseResponse']['Ret'] == 0 
开发者ID:moyuanz,项目名称:DevilYuan,代码行数:33,代码来源:wxbot.py

示例15: QA_fetch_huobi_symbols

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ReadTimeout [as 别名]
def QA_fetch_huobi_symbols():
    """
    Get Symbol and currencies
    """
    url = urljoin(Huobi_base_url, "/v1/common/symbols")
    retries = 1
    datas = list()
    while (retries != 0):
        try:
            req = requests.get(url, timeout=TIMEOUT)
            retries = 0
        except (ConnectTimeout, ConnectionError, SSLError, ReadTimeout):
            retries = retries + 1
            if (retries % 6 == 0):
                print(ILOVECHINA)
            print("Retry get_exchange_info #{}".format(retries - 1))
            time.sleep(0.5)
    if (retries == 0):
        msg_dict = json.loads(req.content)
        if (('status' in msg_dict) and (msg_dict['status'] == 'ok')
                and ('data' in msg_dict)):
            if len(msg_dict["data"]) == 0:
                return []
            for symbol in msg_dict["data"]:
                # 只导入上架交易对
                if (symbol['state'] == 'online'):
                    datas.append(symbol)

    return datas 
开发者ID:QUANTAXIS,项目名称:QUANTAXIS,代码行数:31,代码来源:QAhuobi.py


注:本文中的requests.exceptions.ReadTimeout方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。