當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。