Mercurial > libervia-backend
comparison sat/tools/utils.py @ 3715:b9718216a1c0 0.9
merge bookmark 0.9
author | Goffi <goffi@goffi.org> |
---|---|
date | Wed, 01 Dec 2021 16:13:31 +0100 |
parents | aa58451b77ba |
children | 0a87cae85746 |
comparison
equal
deleted
inserted
replaced
3714:af09b5aaa5d7 | 3715:b9718216a1c0 |
---|---|
26 import sys | 26 import sys |
27 import random | 27 import random |
28 import inspect | 28 import inspect |
29 import textwrap | 29 import textwrap |
30 import functools | 30 import functools |
31 from asyncio import iscoroutine | 31 import asyncio |
32 from twisted.python import procutils, failure | 32 from twisted.python import procutils, failure |
33 from twisted.internet import defer | 33 from twisted.internet import defer |
34 from sat.core.constants import Const as C | 34 from sat.core.constants import Const as C |
35 from sat.core.log import getLogger | 35 from sat.core.log import getLogger |
36 | 36 |
100 try: | 100 try: |
101 ret = func(*args, **kwargs) | 101 ret = func(*args, **kwargs) |
102 except Exception as e: | 102 except Exception as e: |
103 return defer.fail(failure.Failure(e)) | 103 return defer.fail(failure.Failure(e)) |
104 else: | 104 else: |
105 if iscoroutine(ret): | 105 if asyncio.iscoroutine(ret): |
106 return defer.ensureDeferred(ret) | 106 return defer.ensureDeferred(ret) |
107 elif isinstance(ret, defer.Deferred): | 107 elif isinstance(ret, defer.Deferred): |
108 return ret | 108 return ret |
109 elif isinstance(ret, failure.Failure): | 109 elif isinstance(ret, failure.Failure): |
110 return defer.fail(ret) | 110 return defer.fail(ret) |
111 else: | 111 else: |
112 return defer.succeed(ret) | 112 return defer.succeed(ret) |
113 | |
114 | |
115 def aio(func): | |
116 """Decorator to return a Deferred from asyncio coroutine | |
117 | |
118 Functions with this decorator are run in asyncio context | |
119 """ | |
120 def wrapper(*args, **kwargs): | |
121 return defer.Deferred.fromFuture(asyncio.ensure_future(func(*args, **kwargs))) | |
122 return wrapper | |
123 | |
124 | |
125 def as_future(d): | |
126 return d.asFuture(asyncio.get_event_loop()) | |
127 | |
128 | |
129 def ensure_deferred(func): | |
130 """Decorator to apply ensureDeferred to a function | |
131 | |
132 to be used when the function is called by third party library (e.g. wokkel) | |
133 Otherwise, it's better to use ensureDeferred as early as possible. | |
134 """ | |
135 def wrapper(*args, **kwargs): | |
136 return defer.ensureDeferred(func(*args, **kwargs)) | |
137 return wrapper | |
113 | 138 |
114 | 139 |
115 def xmpp_date(timestamp=None, with_time=True): | 140 def xmpp_date(timestamp=None, with_time=True): |
116 """Return date according to XEP-0082 specification | 141 """Return date according to XEP-0082 specification |
117 | 142 |