MyAcc: css
[myslice.git] / manifold / util / callback.py
1 from manifold.operators      import LAST_RECORD
2 import threading
3
4 #------------------------------------------------------------------
5 # Class callback
6 #------------------------------------------------------------------
7
8 class Callback:
9     def __init__(self, deferred=None, router=None, cache_id=None):
10     #def __init__(self, deferred=None, event=None, router=None, cache_id=None):
11         self.results = []
12         self._deferred = deferred
13
14         #if not self.event:
15         self.event = threading.Event()
16         #else:
17         #    self.event = event
18
19         # Used for caching...
20         self.router = router
21         self.cache_id = cache_id
22
23     def __call__(self, value):
24         # End of the list of records sent by Gateway
25         if value == LAST_RECORD:
26             if self.cache_id:
27                 # Add query results to cache (expires in 30min)
28                 #print "Result added to cached under id", self.cache_id
29                 self.router.cache[self.cache_id] = (self.results, time.time() + CACHE_LIFETIME)
30
31             if self._deferred:
32                 # Send results back using deferred object
33                 self._deferred.callback(self.results)
34             else:
35                 # Not using deferred, trigger the event to return results
36                 self.event.set()
37             return self.event
38
39         # Not LAST_RECORD add the value to the results
40         self.results.append(value)
41
42     def wait(self):
43         self.event.wait()
44         self.event.clear()
45
46     def get_results(self):
47         self.wait()
48         return self.results
49