MCPcopy Index your code
hub / github.com/clips/pattern / AsynchronousRequest

Class AsynchronousRequest

pattern/web/__init__.py:96–141  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

94#### ASYNCHRONOUS REQUEST ##########################################################################
95
96class AsynchronousRequest(object):
97
98 def __init__(self, function, *args, **kwargs):
99 """ Executes the function in the background.
100 AsynchronousRequest.done is False as long as it is busy, but the program will not halt in the meantime.
101 AsynchronousRequest.value contains the function's return value once done.
102 AsynchronousRequest.error contains the Exception raised by an erronous function.
103 For example, this is useful for running live web requests while keeping an animation running.
104 For good reasons, there is no way to interrupt a background process (i.e. Python thread).
105 You are responsible for ensuring that the given function doesn't hang.
106 """
107 self._response = None # The return value of the given function.
108 self._error = None # The exception (if any) raised by the function.
109 self._time = time.time()
110 self._function = function
111 self._thread = threading.Thread(target=self._fetch, args=(function,)+args, kwargs=kwargs)
112 self._thread.start()
113
114 def _fetch(self, function, *args, **kwargs):
115 """ Executes the function and sets AsynchronousRequest.response.
116 """
117 try:
118 self._response = function(*args, **kwargs)
119 except Exception, e:
120 self._error = e
121
122 def now(self):
123 """ Waits for the function to finish and yields its return value.
124 """
125 self._thread.join(); return self._response
126
127 @property
128 def elapsed(self):
129 return time.time() - self._time
130 @property
131 def done(self):
132 return not self._thread.isAlive()
133 @property
134 def value(self):
135 return self._response
136 @property
137 def error(self):
138 return self._error
139
140 def __repr__(self):
141 return "AsynchronousRequest(function='%s')" % self._function.__name__
142
143def asynchronous(function, *args, **kwargs):
144 """ Returns an AsynchronousRequest object for the given function.

Callers 1

asynchronousFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…