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


Python gevent.Timeout方法代碼示例

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


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

示例1: test_whatever_1

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def test_whatever_1(self):
        """
        From a writing child, fire into the pipe. In a greenlet in the parent,
        receive one of these messages and return it to the main greenlet.
        Expect message retrieval (child process creation) within a certain
        timeout interval. Terminate the child process after retrieval.
        """
        with pipe() as (r, w):
            def readgreenlet(reader):
                with gevent.Timeout(SHORTTIME * 5, False) as t:
                    m = reader.get(timeout=t)
                    return m
            p = start_process(usecase_child_a, args=(w, ))
            # Wait for process to send first message:
            r.get()
            # Second message must be available immediately now.
            g = gevent.spawn(readgreenlet, r)
            m = r.get()
            assert g.get() == "SPLASH"
            p.terminate()
            p.join()
            assert p.exitcode == -signal.SIGTERM 
開發者ID:jgehrcke,項目名稱:gipc,代碼行數:24,代碼來源:test_gipc.py

示例2: handle

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def handle(self, sock, addr):

        logger.debug('Incomming connection %s:%s', *addr[:2])

        if self.relay and not addr[0] in self.remoteaddr:
            logger.debug('Not in remoteaddr', *addr[:2])
            return 
        try:
            with Timeout(self.timeout, ConnectionTimeout):
                sc = SMTPChannel(self, sock, addr, self.data_size_limit)
                while not sc.closed:
                    sc.handle_read()

        except ConnectionTimeout:
            logger.warn('%s:%s Timeouted', *addr[:2])
            try:
                sc.smtp_TIMEOUT()
            except Exception as err:
                logger.debug(err)
        except Exception as err:
            logger.error(err)

    # API for "doing something useful with the message" 
開發者ID:34nm,項目名稱:gsmtpd,代碼行數:25,代碼來源:server.py

示例3: wait_msg

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def wait_msg(self, event, timeout=None, raises=None):
        """Wait for a message, similiar to :meth:`.wait_event`

        :param event: event id
        :type  event: :class:`.EMsg` or :class:`str`
        :param timeout: seconds to wait before timeout
        :type  timeout: :class:`int`
        :param raises: On timeout when ``False`` returns :class:`None`, else raise :class:`gevent.Timeout`
        :type  raises: :class:`bool`
        :return: returns a message or :class:`None`
        :rtype: :class:`None`, or `proto message`
        :raises: :class:`gevent.Timeout`
        """
        resp = self.wait_event(event, timeout, raises)

        if resp is not None:
            return resp[0] 
開發者ID:ValvePython,項目名稱:steam,代碼行數:19,代碼來源:__init__.py

示例4: send_job_and_wait

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def send_job_and_wait(self, message, body_params=None, timeout=None, raises=False):
        """Send a message as a job and wait for the response.

        .. note::
            Not all messages are jobs, you'll have to find out which are which

        :param message: a message instance
        :type  message: :class:`.Msg`, :class:`.MsgProto`
        :param body_params: a dict with params to the body (only :class:`.MsgProto`)
        :type  body_params: dict
        :param timeout: (optional) seconds to wait
        :type  timeout: :class:`int`
        :param raises: (optional) On timeout if ``False`` return ``None``, else raise :class:`gevent.Timeout`
        :type  raises: :class:`bool`
        :return: response proto message
        :rtype: :class:`.Msg`, :class:`.MsgProto`
        :raises: :class:`gevent.Timeout`
        """
        job_id = self.send_job(message, body_params)
        response = self.wait_event(job_id, timeout, raises=raises)
        if response is None:
            return None
        return response[0].body 
開發者ID:ValvePython,項目名稱:steam,代碼行數:25,代碼來源:__init__.py

示例5: send_message_and_wait

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def send_message_and_wait(self, message, response_emsg, body_params=None, timeout=None, raises=False):
        """Send a message to CM and wait for a defined answer.

        :param message: a message instance
        :type  message: :class:`.Msg`, :class:`.MsgProto`
        :param response_emsg: emsg to wait for
        :type  response_emsg: :class:`.EMsg`,:class:`int`
        :param body_params: a dict with params to the body (only :class:`.MsgProto`)
        :type  body_params: dict
        :param timeout: (optional) seconds to wait
        :type  timeout: :class:`int`
        :param raises: (optional) On timeout if ``False`` return ``None``, else raise :class:`gevent.Timeout`
        :type  raises: :class:`bool`
        :return: response proto message
        :rtype: :class:`.Msg`, :class:`.MsgProto`
        :raises: :class:`gevent.Timeout`
        """
        self.send(message, body_params)
        response = self.wait_event(response_emsg, timeout, raises=raises)
        if response is None:
            return None
        return response[0].body 
開發者ID:ValvePython,項目名稱:steam,代碼行數:24,代碼來源:__init__.py

示例6: test_connect

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def test_connect(self, mock_recv, mock_emit):
        # setup
        self.conn.connect.return_value = True
        self.server_list.__len__.return_value = 10

        # run
        cm = CMClient()

        with gevent.Timeout(2, False):
            cm.connect(retry=1)

        gevent.idle()

        # verify
        self.conn.connect.assert_called_once_with((127001, 20000))
        mock_emit.assert_called_once_with('connected')
        mock_recv.assert_called_once_with() 
開發者ID:ValvePython,項目名稱:steam,代碼行數:19,代碼來源:test_core_cm.py

示例7: test_connect_auto_discovery_failing

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def test_connect_auto_discovery_failing(self, mock_recv, mock_emit):
        # setup
        self.conn.connect.return_value = True
        self.server_list.__len__.return_value = 0

        # run
        cm = CMClient()

        with gevent.Timeout(3, False):
            cm.connect(retry=1)

        gevent.idle()

        # verify
        self.server_list.bootstrap_from_webapi.assert_called_once_with()
        self.server_list.bootstrap_from_dns.assert_called_once_with()
        self.conn.connect.assert_not_called() 
開發者ID:ValvePython,項目名稱:steam,代碼行數:19,代碼來源:test_core_cm.py

示例8: send_message

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def send_message(self, message, timeout=30):
        """
        send message
        :param message: object which can be encoded by msg_encoder (by default json encoder)
        :param timeout: send timeout in second, if timeout, gevent.Timeout exception will be raised
        :return:
        """
        if self.server_terminated:
            raise Exception('Already closed: {0}'.format(self))
        if self._pingpong_trigger:
            self._last_active_ts = get_monotonic_time()
        with gevent.Timeout(seconds=timeout):
            self.send(self._msg_encoder.encode(message), binary=False)
        #log.debug("Sent message to {0}: {1}".format(self, self._msg_encoder.encode(message)))

    # transport session interface methods 
開發者ID:OpenSight,項目名稱:janus-cloud,代碼行數:18,代碼來源:ws.py

示例9: GetAUTH

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def GetAUTH(self):
        '''
        AUTH method
        '''
        try:
           self._response['HELLOTS'] = AsyncResult()
           self._write(AceRequest.HELLOBG())
           paramsdict = self._response['HELLOTS'].get(timeout=self._responsetimeout)
        except gevent.Timeout as t:
           raise AceException('Engine response time %s exceeded. HELLOTS not resived!' % t)
        try:
           self._response['AUTH'] = AsyncResult()
           self._response['NOTREADY'] = AsyncResult()
           self._write(AceRequest.READY(paramsdict.get('key'), self._product_key))
           auth_level = self._response['AUTH'].get(timeout=self._responsetimeout)
           if int(paramsdict.get('version_code', 0)) >= 3003600:
              self._write(AceRequest.SETOPTIONS({'use_stop_notifications': '1'}))
        except gevent.Timeout as t:
           if self._response['NOTREADY'].value:
              errmsg = 'Engine response time %s exceeded. %s resived!' % (t, self._response['NOTREADY'].value)
           else:
              errmsg = 'Engine response time %s exceeded. AUTH not resived!' % t
           raise AceException(errmsg) 
開發者ID:pepsik-kiev,項目名稱:HTTPAceProxy,代碼行數:25,代碼來源:aceclient.py

示例10: gen_traffic

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def gen_traffic(self, url):
        domain = get_domain_from_url(url)
        # add cookie to DEFAULT_HEADER
        cookie = get_cookie(domain)
        self.DEFAULT_HEADER['Cookie'] = cookie
        # add referer
        self.DEFAULT_HEADER['Referer'] = 'https"//' + domain + '/'
        request = HttpRequest(method='GET', url=url, headers=self.DEFAULT_HEADER, body='')
        req = urllib2.Request(url=url, headers=self.DEFAULT_HEADER)
        with gevent.Timeout(10, False)as t:
            try:
                resp = urllib2.urlopen(req)
            except urllib2.URLError, e:
                REQUEST_ERROR.append(('gen_traffic()', url, e.reason))
            except CertificateError:
                REQUEST_ERROR.append(('gen_traffic()', url, 'ssl.CertificateError')) 
開發者ID:lwzSoviet,項目名稱:NoXss,代碼行數:18,代碼來源:engine.py

示例11: request_and_verify

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def request_and_verify(case):
        vul = case.vul
        method = case.method
        url = case.url
        headers = case.headers
        body = case.body
        args = case.args
        old_param = args[2]
        old_value = args[3]
        print 'Verify case use:\n%s' % url
        # time out
        with gevent.Timeout(20, False)as t:
            resp = make_request(method, url, headers, body)
            if resp:
                if Verify.verify(resp, args):
                    poc = gen_poc(method, url, body, old_param, old_value)
                    print_warn('Found %s in %s' % (vul, poc))
                    result = (vul, url, poc)
                    return result
            # count++ when error happened
            else:
                Verify.ERROR_COUNT += 1 
開發者ID:lwzSoviet,項目名稱:NoXss,代碼行數:24,代碼來源:engine.py

示例12: gevent_timeout_deco

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def gevent_timeout_deco(timeout_t):
    def _gevent_timeout_deco(f):
        def __gevent_timeout_deceo(*args, **kwargs):
            timeout = gevent.Timeout(timeout_t, )
            timeout.start()
            result = None
            try:
                result = f(*args, **kwargs)
            except gevent.Timeout as t:
                logger_gevent_timeout_deco.error(f'函數 {f} 運行超過了 {timeout_t} 秒')
                if t is not timeout:
                    nb_print(t)
                    # raise  # not my timeout
            finally:
                timeout.close()
                return result

        return __gevent_timeout_deceo

    return _gevent_timeout_deco 
開發者ID:ydf0509,項目名稱:distributed_framework,代碼行數:22,代碼來源:custom_gevent_pool_executor.py

示例13: test_long_polling_end_no_concurrent_limit

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def test_long_polling_end_no_concurrent_limit(
        client, client_ip, mocker, test_application, test_application_token):
    mocker.patch.object(settings, 'CONCURRENT_LIMITER_SETTINGS', {
        '__default__': {
            'ttl': 100,
            'capacity': 1,
        }
    })
    data = {
        'service': {
            test_application.application_name: ['foo'],
        },
    }
    result = []

    for _ in range(3):
        response = client.post(
            '/api/data/long-polling', headers={
                'Authorization': test_application_token,
            }, query_string={'life_span': 1},
            content_type='application/json', data=json.dumps(data))
        with gevent.Timeout(2):
            list(response.response)
        result.append(response.status_code)
    assert 429 not in result 
開發者ID:huskar-org,項目名稱:huskar,代碼行數:27,代碼來源:test_http_concurrent_limit.py

示例14: _stop_client

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def _stop_client(self):
        """Best effort to stop the client."""
        try:
            # Make sure not to mistake this scenario with failing to stop
            # client.
            if self._client is None:
                log.info("Kazoo client is None.")
                return

            _retry((Exception,), tries=3, delay=1, backoff=2,
                   sleep_func=gevent.sleep)(self._client.stop)()

            log.info("Successfully stopped kazoo client.")
        except (Exception, gevent.Timeout):
            self._sc.increment("errors.zk.client.stop.failure",
                               tags={'host': hostname},
                               sample_rate=1)
            log.exception("Failed to stop kazoo client.") 
開發者ID:pinterest,項目名稱:kingpin,代碼行數:20,代碼來源:__init__.py

示例15: populate

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import Timeout [as 別名]
def populate():
    print("Begin MAC Address population ...")
    try:
        with Timeout(300):
            oui.update()
    except Exception as e:
        print(e)
        print(traceback.format_exc())
    # Response needed for local execution which runs shorter than 2 mins
    finally:
        data = {
            'message': 'Whoaa! MacReduce Data Populated/Refreshed'
        }
        message = json.dumps(data)
        print(message)
        resp = Response(message, status=200, mimetype='application/json')
        return resp 
開發者ID:ibmjstart,項目名稱:bluemix-python-eve-sample,代碼行數:19,代碼來源:home.py


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