本文整理汇总了Python中txaio.as_future函数的典型用法代码示例。如果您正苦于以下问题:Python as_future函数的具体用法?Python as_future怎么用?Python as_future使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了as_future函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: onClose
def onClose(self, wasClean):
"""
Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onClose`
"""
self._transport = None
if self._session_id:
# fire callback and close the transport
d = txaio.as_future(
self.onLeave,
types.CloseDetails(
reason=types.CloseDetails.REASON_TRANSPORT_LOST,
message="WAMP transport was lost without closing the session before",
),
)
def _error(e):
return self._swallow_error(e, "While firing onLeave")
txaio.add_callbacks(d, None, _error)
self._session_id = None
d = txaio.as_future(self.onDisconnect, wasClean)
def _error(e):
return self._swallow_error(e, "While firing onDisconnect")
txaio.add_callbacks(d, None, _error)
示例2: test_explicit_reactor_coroutine
def test_explicit_reactor_coroutine(framework):
"""
If we set an event-loop, Futures + Tasks should use it.
"""
pytest.importorskip('asyncio')
if txaio.using_twisted:
pytest.skip()
from asyncio import coroutine
@coroutine
def some_coroutine():
yield 'nothing'
with patch.object(txaio.config, 'loop') as fake_loop:
txaio.as_future(some_coroutine)
if sys.version_info < (3, 4, 2):
assert len(fake_loop.method_calls) == 2
c = fake_loop.method_calls[1]
assert c[0] == 'call_soon'
else:
assert len(fake_loop.method_calls) == 1
c = fake_loop.method_calls[0]
assert c[0] == 'create_task'
示例3: test_as_future_recursive
def test_as_future_recursive(framework):
'''
Returns another Future from as_future
'''
errors = []
results = []
calls = []
f1 = txaio.create_future_success(42)
def method(*args, **kw):
calls.append((args, kw))
return f1
f0 = txaio.as_future(method, 1, 2, 3, key='word')
def cb(x):
results.append(x)
def errback(f):
errors.append(f)
txaio.add_callbacks(f0, cb, errback)
run_once()
assert len(results) == 1
assert len(errors) == 0
assert results[0] == 42
assert calls[0] == ((1, 2, 3), dict(key='word'))
示例4: test_as_future_exception
def test_as_future_exception(framework):
'''
Raises an exception from as_future
'''
errors = []
results = []
calls = []
exception = RuntimeError("sadness")
def method(*args, **kw):
calls.append((args, kw))
raise exception
f = txaio.as_future(method, 1, 2, 3, key='word')
def cb(x):
results.append(x)
def errback(f):
errors.append(f)
txaio.add_callbacks(f, cb, errback)
run_once()
assert len(results) == 0
assert len(errors) == 1
assert errors[0].value == exception
assert calls[0] == ((1, 2, 3), dict(key='word'))
示例5: test_as_future_immediate_none
def test_as_future_immediate_none(framework):
'''
Returning None immediately from as_future
'''
errors = []
results = []
calls = []
def method(*args, **kw):
calls.append((args, kw))
return None
f = txaio.as_future(method, 1, 2, 3, key='word')
def cb(x):
results.append(x)
def errback(f):
errors.append(f)
txaio.add_callbacks(f, cb, errback)
run_once()
assert len(results) == 1
assert len(errors) == 0
assert results[0] is None
assert calls[0] == ((1, 2, 3), dict(key='word'))
示例6: fire
def fire(self, event, *args, **kwargs):
res = []
if event in self._listeners:
for handler in self._listeners[event]:
value = txaio.as_future(handler, *args, **kwargs)
res.append(value)
if self._parent is not None:
res.append(self._parent.fire(event, *args, **kwargs))
return txaio.gather(res)
示例7: component_start
def component_start(comp):
# the future from start() errbacks if we fail, or callbacks
# when the component is considered "done" (so maybe never)
d = txaio.as_future(comp.start, reactor)
txaio.add_callbacks(
d,
partial(component_success, comp),
partial(component_failure, comp),
)
return d
示例8: onOpen
def onOpen(self, transport):
"""
Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onOpen`
"""
self._transport = transport
d = txaio.as_future(self.onConnect)
def _error(e):
return self._swallow_error(e, "While firing onConnect")
txaio.add_callbacks(d, None, _error)
示例9: on_join
def on_join(session, details):
self.log.debug("session on_join: {details}", details=details)
d = txaio.as_future(self._entry, reactor, session)
def setup_success(_):
self.log.debug("setup_success")
def setup_error(err):
self.log.debug("setup_error", err)
txaio.add_callbacks(d, setup_success, setup_error)
示例10: test_gather_two
def test_gather_two():
'''
Wait for two Futures.
'''
errors = []
results = []
calls = []
def foo():
def codependant(*args, **kw):
calls.append((args, kw))
return 42
return txaio.as_future(codependant)
def method(*args, **kw):
calls.append((args, kw))
return "OHAI"
f0 = txaio.as_future(method, 1, 2, 3, key='word')
f1 = txaio.as_future(foo)
f2 = txaio.gather([f0, f1])
def done(arg):
results.append(arg)
def error(fail):
errors.append(fail)
# fail.printTraceback()
txaio.add_callbacks(f2, done, error)
await(f0)
await(f1)
await(f2)
assert len(results) == 1
assert len(errors) == 0
assert results[0] == ['OHAI', 42] or results[0] == [42, 'OHAI']
assert len(calls) == 2
assert calls[0] == ((1, 2, 3), dict(key='word'))
assert calls[1] == (tuple(), dict())
示例11: authorize
def authorize(self, session, uri, action, options):
"""
Authorizes a session for an action on an URI.
Implements :func:`autobahn.wamp.interfaces.IRouter.authorize`
"""
assert(type(uri) == str)
assert(action in [u'call', u'register', u'publish', u'subscribe'])
# the role under which the session that wishes to perform the given action on
# the given URI was authenticated under
role = session._authrole
if role in self._roles:
# the authorizer procedure of the role which we will call ..
authorize = self._roles[role].authorize
d = txaio.as_future(authorize, session, uri, action, options)
else:
# normally, the role should exist on the router (and hence we should not arrive
# here), but the role might have been dynamically removed - and anyway, safety first!
d = txaio.create_future_success(False)
# XXX would be nicer for dynamic-authorizer authors if we
# sanity-checked the return-value ('authorization') here
# (i.e. is it a dict? does it have 'allow' in it? does it have
# disallowed keys in it?)
def got_authorization(authorization):
# backward compatibility
if isinstance(authorization, bool):
authorization = {
u'allow': authorization,
u'cache': False
}
if action in [u'call', u'publish']:
authorization[u'disclose'] = False
auto_disclose_trusted = False
if auto_disclose_trusted and role == u'trusted' and action in [u'call', u'publish']:
authorization[u'disclose'] = True
self.log.debug("Authorized action '{action}' for URI '{uri}' by session {session_id} with authid '{authid}' and authrole '{authrole}' -> authorization: {authorization}",
session_id=session._session_id,
uri=uri,
action=action,
authid=session._authid,
authrole=session._authrole,
authorization=authorization)
return authorization
d.addCallback(got_authorization)
return d
示例12: error
def error(err):
reply = message.Abort(u"wamp.error.cannot_authenticate", u"{0}".format(err.value))
self._transport.send(reply)
# fire callback and close the transport
details = types.CloseDetails(reply.reason, reply.message)
d = txaio.as_future(self.onLeave, details)
def _error(e):
return self._swallow_error(e, "While firing onLeave")
txaio.add_callbacks(d, None, _error)
# switching to the callback chain, effectively
# cancelling error (which we've now handled)
return d
示例13: stop
def stop(self):
self._stopping = True
if self._session and self._session.is_attached():
return self._session.leave()
elif self._delay_f:
# This cancel request will actually call the "error" callback of
# the _delay_f future. Nothing to worry about.
return txaio.as_future(txaio.cancel, self._delay_f)
# if (for some reason -- should we log warning here to figure
# out if this can evern happen?) we've not fired _done_f, we
# do that now (causing our "main" to exit, and thus react() to
# quit)
if not txaio.is_called(self._done_f):
txaio.resolve(self._done_f, None)
return txaio.create_future_success(None)
示例14: authorize
def authorize(self, session, uri, action):
"""
Authorizes a session for an action on an URI.
Implements :func:`autobahn.wamp.interfaces.IRouter.authorize`
"""
assert(type(uri) == six.text_type)
assert(action in [u'call', u'register', u'publish', u'subscribe'])
# the role under which the session that wishes to perform the given action on
# the given URI was authenticated under
role = session._authrole
if role in self._roles:
# the authorizer procedure of the role which we will call ..
authorize = self._roles[role].authorize
d = txaio.as_future(authorize, session, uri, action)
else:
# normally, the role should exist on the router (and hence we should not arrive
# here), but the role might have been dynamically removed - and anyway, safety first!
d = txaio.create_future_success(False)
def got_authorization(authorization):
# backward compatibility
if type(authorization) == bool:
authorization = {
u'allow': authorization,
u'cache': False
}
if action in [u'call', u'publish']:
authorization[u'disclose'] = False
self.log.debug("Authorized action '{action}' for URI '{uri}' by session {session_id} with authid '{authid}' and authrole '{authrole}' -> authorization: {authorization}",
session_id=session._session_id,
uri=uri,
action=action,
authid=session._authid,
authrole=session._authrole,
authorization=authorization)
return authorization
d.addCallback(got_authorization)
return d
示例15: on_join
def on_join(session, details):
transport.connect_sucesses += 1
self.log.debug("session on_join: {details}", details=details)
d = txaio.as_future(self._entry, reactor, session)
def main_success(_):
self.log.debug("main_success")
def leave():
try:
session.leave()
except SessionNotReady:
# someone may have already called
# leave()
pass
txaio.call_later(0, leave)
def main_error(err):
self.log.debug("main_error: {err}", err=err)
txaio.reject(done, err)
session.disconnect()
txaio.add_callbacks(d, main_success, main_error)