本文整理匯總了Python中gevent.event.AsyncResult方法的典型用法代碼示例。如果您正苦於以下問題:Python event.AsyncResult方法的具體用法?Python event.AsyncResult怎麽用?Python event.AsyncResult使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類gevent.event
的用法示例。
在下文中一共展示了event.AsyncResult方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: GetAUTH
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [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)
示例2: run_query
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def run_query(self, query, noreply):
self._write_mutex.acquire()
try:
self._socket.sendall(query.serialize(self._parent._get_json_encoder(query)))
finally:
self._write_mutex.release()
if noreply:
return None
async_res = AsyncResult()
self._user_queries[query.token] = (query, async_res)
return async_res.get()
# The _reader coroutine runs in its own coroutine in parallel, reading responses
# off of the socket and forwarding them to the appropriate AsyncResult or Cursor.
# This is shut down as a consequence of closing the stream, or an error in the
# socket/protocol from the server. Unexpected errors in this coroutine will
# close the ConnectionInstance and be passed to any open AsyncResult or Cursors.
示例3: test_eventual_lowering
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def test_eventual_lowering():
result = AsyncResult()
e = Eventual(lambda: result.set(datetime.utcnow()))
e.set_next_schedule(
datetime.utcnow() + timedelta(seconds=10)
)
e.set_next_schedule(
datetime.utcnow() + timedelta(seconds=5)
)
should_be_called_at = datetime.utcnow() + timedelta(milliseconds=100)
e.set_next_schedule(should_be_called_at)
called_at = result.get()
assert called_at >= should_be_called_at
assert called_at <= should_be_called_at + timedelta(milliseconds=100)
示例4: wait_for_message
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def wait_for_message(self, emsg, timeout=None):
if not emsg in self.message_events:
#print emsg, 'not registered!'
return None
while True:
if emsg != EMsg.ChannelEncryptResult and emsg != EMsg.ClientLogOnResponse:
self.logon_event.wait()
if not self.connection.connected:
raise Exception("Not connected, unable to send message")
if self.message_events[emsg]:
async_result = self.message_events[emsg]
else:
async_result = self.message_events[emsg] = AsyncResult()
try:
return async_result.get(timeout=timeout)
except Timeout:
return 'Timed Out'
except Exception:
pass
示例5: wait_for_job
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def wait_for_job(self, message, emsg):
jobid = self.jobid
self.jobid += 1
message.header.source_jobid = jobid
while True:
self.logon_event.wait()
if not self.connection.connected:
raise Exception("Not connected, unable to send message")
self.connection.send_message(message)
async_result = self.message_job_events[jobid] = AsyncResult()
try:
return async_result.get()
except Exception as e:
pass
示例6: publish
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def publish(self, topic, data, defer=None, block=True, timeout=None,
raise_error=True):
"""Publish a message to the given topic.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publishing
(requires nsq 0.3.6)
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
are available, :class:`~gnsq.errors.NSQNoConnections` is raised
:param timeout: if timeout is a positive number, it blocks at most
``timeout`` seconds before raising
:class:`~gnsq.errors.NSQNoConnections`
:param raise_error: if ``True``, it blocks until a response is received
from the nsqd server, and any error response is raised. Otherwise
an :class:`~gevent.event.AsyncResult` is returned
"""
result = AsyncResult()
conn = self._get_connection(block=block, timeout=timeout)
try:
self._response_queues[conn].append(result)
conn.publish(topic, data, defer=defer)
finally:
self._put_connection(conn)
if raise_error:
return result.get()
return result
示例7: multipublish
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def multipublish(self, topic, messages, block=True, timeout=None,
raise_error=True):
"""Publish an iterable of messages to the given topic.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
are available, :class:`~gnsq.errors.NSQNoConnections` is raised
:param timeout: if timeout is a positive number, it blocks at most
``timeout`` seconds before raising
:class:`~gnsq.errors.NSQNoConnections`
:param raise_error: if ``True``, it blocks until a response is received
from the nsqd server, and any error response is raised. Otherwise
an :class:`~gevent.event.AsyncResult` is returned
"""
result = AsyncResult()
conn = self._get_connection(block=block, timeout=timeout)
try:
self._response_queues[conn].append(result)
conn.multipublish(topic, messages)
finally:
self._put_connection(conn)
if raise_error:
return result.get()
return result
示例8: __init__
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def __init__(self, handler):
self.handler = handler
self.result = AsyncResult()
self.server = StreamServer(('127.0.0.1', 0), self)
示例9: __setup_events
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def __setup_events(self):
self.__readable = AsyncResult()
self.__writable = AsyncResult()
self.__readable.set()
self.__writable.set()
try:
self._state_event = get_hub().loop.io(self.getsockopt(zmq.FD), 1) # read state watcher
self._state_event.start(self.__state_changed)
except AttributeError:
# for gevent<1.0 compatibility
from gevent.core import read_event
self._state_event = read_event(self.getsockopt(zmq.FD), self.__state_changed, persist=True)
示例10: _wait_write
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def _wait_write(self):
assert self.__writable.ready(), "Only one greenlet can be waiting on this event"
self.__writable = AsyncResult()
# timeout is because libzmq cannot be trusted to properly signal a new send event:
# this is effectively a maximum poll interval of 1s
tic = time.time()
dt = self._gevent_bug_timeout
if dt:
timeout = gevent.Timeout(seconds=dt)
else:
timeout = None
try:
if timeout:
timeout.start()
self.__writable.get(block=True)
except gevent.Timeout as t:
if t is not timeout:
raise
toc = time.time()
# gevent bug: get can raise timeout even on clean return
# don't display zmq bug warning for gevent bug (this is getting ridiculous)
if self._debug_gevent and timeout and toc-tic > dt and \
self.getsockopt(zmq.EVENTS) & zmq.POLLOUT:
print("BUG: gevent may have missed a libzmq send event on %i!" % self.FD, file=sys.stderr)
finally:
if timeout:
timeout.cancel()
self.__writable.set()
示例11: _wait_read
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def _wait_read(self):
assert self.__readable.ready(), "Only one greenlet can be waiting on this event"
self.__readable = AsyncResult()
# timeout is because libzmq cannot always be trusted to play nice with libevent.
# I can only confirm that this actually happens for send, but lets be symmetrical
# with our dirty hacks.
# this is effectively a maximum poll interval of 1s
tic = time.time()
dt = self._gevent_bug_timeout
if dt:
timeout = gevent.Timeout(seconds=dt)
else:
timeout = None
try:
if timeout:
timeout.start()
self.__readable.get(block=True)
except gevent.Timeout as t:
if t is not timeout:
raise
toc = time.time()
# gevent bug: get can raise timeout even on clean return
# don't display zmq bug warning for gevent bug (this is getting ridiculous)
if self._debug_gevent and timeout and toc-tic > dt and \
self.getsockopt(zmq.EVENTS) & zmq.POLLIN:
print("BUG: gevent may have missed a libzmq recv event on %i!" % self.FD, file=sys.stderr)
finally:
if timeout:
timeout.cancel()
self.__readable.set()
示例12: __init__
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def __init__(self, params):
# AceEngine product key
self._product_key = params.get('acekey', AceConst.ACE_KEY)
# Current auth
self._gender = params.get('acesex', AceConst.SEX_MALE)
self._age = params.get('aceage', AceConst.AGE_25_34)
# Seekback seconds.
self._seekback = params.get('videoseekback', 0)
# AceEngine API maximum allowable response read delay to receive playback URL
self._videotimeout = params.get('videotimeout', 30)
# AceEngine API maximum allowable response read delay
self._responsetimeout = params.get('result_timeout', 5)
# AceEngine API responses (Created with AsyncResult() on call)
self._response = {}.fromkeys(['HELLOTS','AUTH','NOTREADY','LOADRESP','START','STATE','STATUS','EVENT',
'STOP','PAUSE','RESUME','INFO','SHUTDOWN',], AsyncResult())
# Broadcast title
self._title = 'idleAce'
# AceEngine socket
try:
self._socket = Telnet(params.get('ace')['aceHostIP'], params.get('ace')['aceAPIport'], params.get('connect_timeout', 10))
except:
raise AceException('The are no alive AceStream Engines found!')
else:
# Spawning telnet data reader with recvbuffer read timeout (allowable STATE 0 (IDLE) time)
self._read = gevent.spawn(self._read, self._videotimeout)
self._read.link(lambda x: self._socket.close())
self._read.link(lambda x: logging.debug('[%.20s]: >>> %s' % (self._title, 'CLOSE telnet connetcion')))
示例13: GetBroadcastStartParams
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def GetBroadcastStartParams(self, paramsdict):
'''
Start video method
:return START params dict from AceEngine
If seekback is disabled, we use link in first START command recived from AceEngine.
If seekback is enabled, we wait for first START command and ignore it,
then do seekback in first EVENT livepos command (EVENT livepos only for live translation (stream=1) and url not in hls).
AceEngine sends us STOP and START again with new link. We use only second link then.
'''
try:
self._response['START'] = AsyncResult()
self._write(AceRequest.START(paramsdict))
paramsdict = self._response['START'].get(timeout=self._videotimeout)
if self._seekback and paramsdict.get('stream') and not paramsdict['url'].endswith('.m3u8'):
try:
self._response['EVENT'] = AsyncResult()
paramsdict = self._response['EVENT'].get(timeout=self._responsetimeout)
except gevent.Timeout as t:
raise AceException('EVENT livepos not received! Engine response time %s exceeded' % t)
else:
try:
self._response['START'] = AsyncResult()
self._write(AceRequest.LIVESEEK(int(paramsdict['last']) - self._seekback))
paramsdict = self._response['START'].get(timeout=self._videotimeout)
except gevent.Timeout as t:
raise AceException('START URL not received after LIVESEEK! Engine response time %s exceeded' % t)
return paramsdict
except gevent.Timeout as t:
raise AceException('START URL not received! Engine response time %s exceeded' % t)
示例14: GetLOADASYNC
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def GetLOADASYNC(self, paramsdict):
try:
self._response['LOADRESP'] = AsyncResult()
self._write(AceRequest.LOADASYNC(paramsdict))
return self._response['LOADRESP'].get(timeout=self._responsetimeout) # Get _contentinfo json
except gevent.Timeout as t:
raise AceException('Engine response %s time exceeded. LOADRESP not resived!' % t)
示例15: GetSTATUS
# 需要導入模塊: from gevent import event [as 別名]
# 或者: from gevent.event import AsyncResult [as 別名]
def GetSTATUS(self):
try:
self._response['STATUS'] = AsyncResult()
return self._response['STATUS'].get(timeout=self._responsetimeout) # Get status
except: return {'status': 'error'}