Python requests.exceptions.ReadTimeout() Examples

The following are 30 code examples of requests.exceptions.ReadTimeout(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests.exceptions , or try the search function .
Example #1
Source File: test_blockchain.py    From raiden-services with MIT License 7 votes vote down vote up
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 
Example #2
Source File: input_vectors.py    From FACT_core with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: wxbot.py    From DevilYuan with MIT License 6 votes vote down vote up
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 
Example #4
Source File: qemu_exec.py    From FACT_core with GNU General Public License v3.0 6 votes vote down vote up
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'} 
Example #5
Source File: docker.py    From FACT_core with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #6
Source File: proxy.py    From PatentCrawler with Apache License 2.0 6 votes vote down vote up
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有问题') 
Example #7
Source File: wxbot.py    From DevilYuan with MIT License 6 votes vote down vote up
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 
Example #8
Source File: wxbot.py    From DevilYuan with MIT License 6 votes vote down vote up
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 
Example #9
Source File: wxbot.py    From DevilYuan with MIT License 6 votes vote down vote up
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 
Example #10
Source File: wxbot.py    From wxBot with Apache License 2.0 6 votes vote down vote up
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 
Example #11
Source File: wxbot.py    From wxBot with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: _lambda_build.py    From taskcat with Apache License 2.0 6 votes vote down vote up
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")) 
Example #13
Source File: test_gauge.py    From faucet with Apache License 2.0 5 votes vote down vote up
def test_ship_no_config(self):
        """Check that no exceptions are thrown when
        there is no config"""

        try:
            shipper = gauge_influx.InfluxShipper()
            points = [{'measurement': 'test_stat_name', 'fields' : {'value':1}},]
            shipper.ship_points(points)
        except (ConnectionError, ReadTimeout) as err:
            self.fail("Code threw an exception: {}".format(err)) 
Example #14
Source File: http.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def retry_method(self, method, *args, **kwargs):
        if self.proxies:
            # fixme: may be a little loud
            logger.debug("Using proxy %s for: %s", self.proxies["http"], args[0])

        return retry_call(getattr(super(RetryingSession, self), method), fargs=args, fkwargs=kwargs, tries=3, delay=5,
                          exceptions=(exceptions.ConnectionError,
                                      exceptions.ProxyError,
                                      exceptions.SSLError,
                                      exceptions.Timeout,
                                      exceptions.ConnectTimeout,
                                      exceptions.ReadTimeout,
                                      socket.timeout)) 
Example #15
Source File: wxbot.py    From DevilYuan with MIT License 5 votes vote down vote up
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 
Example #16
Source File: wxbot.py    From DevilYuan with MIT License 5 votes vote down vote up
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 
Example #17
Source File: wxbot.py    From DevilYuan with MIT License 5 votes vote down vote up
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 
Example #18
Source File: wxbot.py    From DevilYuan with MIT License 5 votes vote down vote up
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 
Example #19
Source File: request_handler.py    From Raccoon with MIT License 5 votes vote down vote up
def send(self, method="GET", *args, **kwargs):
        """
        Send a GET/POST/HEAD request using the object's proxies and headers
        :param method: Method to send request in. GET/POST/HEAD
        """
        proxies = self._get_request_proxies()

        try:
            if method.upper() in self.allowed_methods:
                kwargs['timeout'] = kwargs['timeout'] if 'timeout' in kwargs else 5
                return request(method, proxies=proxies, headers=self.headers, cookies=self.cookies, *args, **kwargs)
            else:
                raise RequestHandlerException("Unsupported method: {}".format(method))
        except ProxyError:
            # TODO: Apply fail over for bad proxies or drop them
            raise RequestHandlerException("Error connecting to proxy")
        except (ConnectTimeout, ReadTimeout):
            raise RequestHandlerException("Connection with server timed out")
        except NewConnectionError:
            raise RequestHandlerException("Address cannot be resolved")
            # New connection error == Can't resolve address
        except ConnectionError:
            # TODO: Increase delay
            raise RequestHandlerException("Error connecting to host")
        except TooManyRedirects:
            raise RequestHandlerException("Infinite redirects detected - too many redirects error")
        except UnicodeDecodeError:
            # Following issue #19, apparently some sites do not use utf-8 in their uris :<>
            pass 
Example #20
Source File: test_gauge.py    From faucet with Apache License 2.0 5 votes vote down vote up
def test_ship_success(self):
        """Checks that the shipper successsfully connects
        to a HTTP server when the points are shipped"""

        try:
            server = start_server(PretendInflux)
            shipper = gauge_influx.InfluxShipper()
            shipper.conf = self.create_config_obj(server.server_port)
            points = [{'measurement': 'test_stat_name', 'fields' : {'value':1}},]
            shipper.ship_points(points)
        except (ConnectionError, ReadTimeout) as err:
            self.fail("Code threw an exception: {}".format(err))
        finally:
            server.socket.close()
            server.shutdown() 
Example #21
Source File: requestProxy.py    From HTTP_Request_Randomizer with MIT License 5 votes vote down vote up
def __init__(self, web_proxy_list=[], sustain=False, timeout=5, protocol=Protocol.HTTP):
        self.logger = logging.getLogger()
        self.logger.addHandler(handler)
        self.logger.setLevel(0)
        self.userAgent = UserAgentManager(file=os.path.join(os.path.dirname(__file__), '../data/user_agents.txt'))

        #####
        # Each of the classes below implements a specific URL Parser
        #####
        parsers = list([])
        parsers.append(FreeProxyParser('FreeProxy', 'http://free-proxy-list.net', timeout=timeout))
        #parsers.append(ProxyForEuParser('ProxyForEU', 'http://proxyfor.eu/geo.php', 1.0, timeout=timeout)) <--doesn't work anymore
        #parsers.append(RebroWeeblyParser('ReBro', 'http://rebro.weebly.com', timeout=timeout)) <--doesn't work anymore
        parsers.append(PremProxyParser('PremProxy', 'https://premproxy.com', timeout=timeout))
        parsers.append(SslProxyParser('SslProxy', 'https://www.sslproxies.org', timeout=timeout))

        self.logger.debug("=== Initialized Proxy Parsers ===")
        for i in range(len(parsers)):
            self.logger.debug("\t {0}".format(parsers[i].__str__()))
        self.logger.debug("=================================")

        self.sustain = sustain
        self.parsers = parsers
        self.proxy_list = web_proxy_list
        for parser in parsers:
            try:
                size = len(self.proxy_list)
                self.proxy_list += parser.parse_proxyList()
                self.logger.debug('Added {} proxies from {}'.format(len(self.proxy_list)-size, parser.id))
            except ReadTimeout:
                self.logger.warning("Proxy Parser: '{}' TimedOut!".format(parser.url))
        self.logger.debug('Total proxies = '+str(len(self.proxy_list)))
        # filtering the list of available proxies according to user preferences
        self.proxy_list = [p for p in self.proxy_list if protocol in p.protocols]
        self.logger.debug('Filtered proxies = '+str(len(self.proxy_list)))
        self.current_proxy = self.randomize_proxy() 
Example #22
Source File: wxbot.py    From wxBot with Apache License 2.0 5 votes vote down vote up
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 
Example #23
Source File: wxbot.py    From wxBot with Apache License 2.0 5 votes vote down vote up
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 
Example #24
Source File: wxbot.py    From wxBot with Apache License 2.0 5 votes vote down vote up
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 
Example #25
Source File: wxbot.py    From wxBot with Apache License 2.0 5 votes vote down vote up
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 
Example #26
Source File: sender.py    From AdslProxy with MIT License 5 votes vote down vote up
def test_proxy(self, proxy):
        """
        测试代理
        :param proxy: 代理
        :return: 测试结果
        """
        try:
            response = requests.get(TEST_URL, proxies={
                'http': 'http://' + proxy,
                'https': 'https://' + proxy
            }, timeout=TEST_TIMEOUT)
            if response.status_code == 200:
                return True
        except (ConnectionError, ReadTimeout):
            return False 
Example #27
Source File: virtualhost.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def fingerprint_virtual_host(
        self,
        org_uuid=None,
        network_service_uuid=None,
        network_service_scan_uuid=None,
        use_ssl=None,
        hostname=None,
        order_uuid=None,
):
    """
    Get a virtual host fingerprint from the web service running at the given network service for
    the given hostname.
    :param org_uuid: The UUID of the organization to retrieve a fingerprint for.
    :param network_service_uuid: The UUID of the network service where the web service resides.
    :param network_service_scan_uuid: The UUID of the network service scan that this fingerprinting is a part
    of.
    :param use_ssl: Whether or not to use SSL to connect to the remote endpoint.
    :param hostname: The hostname to submit a request for.
    :return: None
    """
    logger.info(
        "Now retrieving virtual host fingerprint for service %s with hostname %s. Organization is %s."
        % (network_service_uuid, hostname, org_uuid)
    )
    ip_address, port, protocol = self.get_endpoint_information()
    inspector = WebServiceInspector(ip_address=ip_address, port=port, use_ssl=use_ssl, hostname=hostname)
    try:
        response = inspector.get()
    except (SSLError, ReadTimeout) as e:
        logger.error(
            "Error thrown when retrieving fingerprint: %s %s."
            % (e.__class__.__name__, e.message)
        )
        return
    logger.info(
        "Fingerprint retrieved for virtual host %s on service %s."
        % (hostname, network_service_uuid)
    )
    fingerprint_model = response.to_es_model(model_uuid=network_service_scan_uuid, db_session=self.db_session)
    fingerprint_model.save(org_uuid)
    logger.info("Fingerprint pushed to Elasticsearch successfully.") 
Example #28
Source File: connectapiclient.py    From rfapi-python with Apache License 2.0 5 votes vote down vote up
def head_fusion_file(self, path):
        """Make a HEAD http requests for a fusion file.

        Args:
            path: the fusion file path

        Returns:
            the headers as a dict.
        """
        self._check_auth()
        route = 'fusion/files'
        params = self._prepare_params({'path': path})
        headers = self._prepare_headers()

        try:
            LOG.debug("Requesting query path_info=%s", route)
            # don't use session for streams. Might cause issues when
            # downloading many files in parallel and connections are
            # evicted from the urllib3 connection pool prematurely.

            url = self._url + 'fusion/files'
            response = requests.head(url,
                                     params=params,
                                     headers=headers,
                                     auth=self._auth,
                                     proxies=self._proxies,
                                     timeout=self._timeout)
            response.raise_for_status()
        except requests.HTTPError as req_http_err:
            msg = "Exception occurred during path_info: %s. Error was: %s"
            LOG.exception(msg, route, response.content)
            self._raise_http_error(response, req_http_err)

        except ReadTimeout:
            msg = "Read Timeout occured during path_info: %s."
            LOG.exception(msg, route)
            raise
        return response.headers 
Example #29
Source File: test_client.py    From hdfs with MIT License 5 votes vote down vote up
def test_timeout(self):
    self.client._timeout = 1e-4 # Small enough for it to always timeout.
    try:
      self.client.status('.')
    except (ConnectTimeout, ReadTimeout):
      self.client._timeout = None
    else:
      raise HdfsError('No timeout.') 
Example #30
Source File: test_subreddit.py    From rtv with MIT License 5 votes vote down vote up
def test_subreddit_get_inbox_timeout(subreddit_page, refresh_token, terminal, vcr):
    if vcr.record_mode == 'none':
        pytest.skip('Unable to test ReadTimeout exceptions using a cassette')

    # Log in
    subreddit_page.config.refresh_token = refresh_token
    subreddit_page.oauth.authorize()

    subreddit_page.reddit.config.timeout = 0.00000001
    subreddit_page.controller.trigger('i')
    text = 'HTTP request timed out'.encode('utf-8')
    terminal.stdscr.subwin.addstr.assert_called_with(1, 1, text)
    assert isinstance(terminal.loader.exception, ReadTimeout)