本文整理汇总了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
示例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"
示例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]
示例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
示例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
示例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()
示例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()
示例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
示例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)
示例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'))
示例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
示例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
示例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
示例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.")
示例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