Check cache for the data. If it is there, check to see if it needs to be refreshed. If the data is not there, or it needs to be refreshed, then call the callback function (``fun``) with any given ``**kwargs``. In some cases, the callback function returns a
(self, bank, key, fun, loop_fun=None, **kwargs)
| 91 | self._modules = None |
| 92 | |
| 93 | def cache(self, bank, key, fun, loop_fun=None, **kwargs): |
| 94 | """ |
| 95 | Check cache for the data. If it is there, check to see if it needs to |
| 96 | be refreshed. |
| 97 | |
| 98 | If the data is not there, or it needs to be refreshed, then call the |
| 99 | callback function (``fun``) with any given ``**kwargs``. |
| 100 | |
| 101 | In some cases, the callback function returns a list of objects which |
| 102 | need to be processed by a second function. If that is the case, then |
| 103 | the second function is passed in as ``loop_fun``. Each item in the |
| 104 | return list from the first function will be the only argument for the |
| 105 | second function. |
| 106 | """ |
| 107 | expire_seconds = kwargs.get("expire", 86400) # 1 day |
| 108 | |
| 109 | updated = self.updated(bank, key) |
| 110 | update_cache = False |
| 111 | if updated is None: |
| 112 | update_cache = True |
| 113 | else: |
| 114 | if int(time.time()) - updated > expire_seconds: |
| 115 | update_cache = True |
| 116 | |
| 117 | data = self.fetch(bank, key) |
| 118 | |
| 119 | if not data or update_cache is True: |
| 120 | if loop_fun is not None: |
| 121 | data = [] |
| 122 | items = fun(**kwargs) |
| 123 | for item in items: |
| 124 | data.append(loop_fun(item)) |
| 125 | else: |
| 126 | data = fun(**kwargs) |
| 127 | self.store(bank, key, data) |
| 128 | |
| 129 | return data |
| 130 | |
| 131 | def store(self, bank, key, data, expires=None): |
| 132 | """ |