core (tools/utils): new asDeferred function:
asDeferred is similar to defer.maybeCoroutine, and also handles coroutine.
This commit is contained in:
parent
1faa5e82da
commit
31e9cc7cbf
1 changed files with 24 additions and 1 deletions
|
|
@ -29,7 +29,9 @@ import random
|
|||
import inspect
|
||||
import textwrap
|
||||
import functools
|
||||
from twisted.python import procutils
|
||||
from asyncio import iscoroutine
|
||||
from twisted.python import procutils, failure
|
||||
from twisted.internet import defer
|
||||
from sat.core.constants import Const as C
|
||||
from sat.core.log import getLogger
|
||||
|
||||
|
|
@ -90,6 +92,27 @@ def partial(func, *fixed_args, **fixed_kwargs):
|
|||
return method
|
||||
|
||||
|
||||
def asDeferred(func, *args, **kwargs):
|
||||
"""Call a method and return a Deferred
|
||||
|
||||
the method can be a simple callable, a Deferred or a coroutine.
|
||||
It is similar to defer.maybeDeferred, but also handles coroutines
|
||||
"""
|
||||
try:
|
||||
ret = func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
return defer.fail(failure.Failure(e))
|
||||
else:
|
||||
if iscoroutine(ret):
|
||||
return defer.ensureDeferred(ret)
|
||||
elif isinstance(ret, defer.Deferred):
|
||||
return ret
|
||||
elif isinstance(ret, failure.Failure):
|
||||
return defer.fail(ret)
|
||||
else:
|
||||
return ret
|
||||
|
||||
|
||||
def xmpp_date(timestamp=None, with_time=True):
|
||||
"""Return date according to XEP-0082 specification
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue