Skip to content

Commit

Permalink
Force caching of the API object to 5 seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
erwan committed Nov 12, 2014
1 parent 517da4b commit d6cebc1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
6 changes: 3 additions & 3 deletions prismic/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ def get(url, access_token=None, cache=None):
:param url: URL to the api of the repository.
:param access_token: The access token.
"""
return Api(_get_json(url, access_token=access_token, cache=cache), access_token, cache)
return Api(_get_json(url, access_token=access_token, cache=cache, ttl=5), access_token, cache)


def _get_json(url, params=None, access_token=None, cache=None):
def _get_json(url, params=None, access_token=None, cache=None, ttl=None):
full_params = dict() if params is None else params.copy()
if cache is None:
cache = ShelveCache(re.sub(r'/\\', '', url.split('/')[2]))
Expand All @@ -65,7 +65,7 @@ def _get_json(url, params=None, access_token=None, cache=None):
if not isinstance(text_result, str):
text_result = text_result.decode('utf-8')
json_result = json.loads(text_result, object_pairs_hook=OrderedDict)
expire = _max_age(response)
expire = ttl or _max_age(response)
if expire is not None:
cache.set(full_url, json_result, expire)
return json_result
Expand Down
9 changes: 5 additions & 4 deletions prismic/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class NoCache(object):
"""
pass

def set(self, key, val, time=0):
def set(self, key, val, ttl=0):
pass

def get(self, key):
Expand All @@ -39,21 +39,22 @@ def _init_db(self):
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
self.db = shelve.open(os.path.join(cache_dir, self.filename))
print("Shelf dir = " + cache_dir)

def set(self, key, val, time=0):
def set(self, key, val, ttl=0):
self._init_db()
if type(key) != str:
key = key.encode('utf8')
self.db[key] = {
"val": val,
"expire": ShelveCache.unix_time() + time
"expire": ShelveCache.unix_time() + ttl
}

def get(self, key):
self._init_db()
if type(key) != str:
key = key.encode('utf8')
if not key in self.db:
if key not in self.db:
return None
d = self.db[key]
if d["expire"] < ShelveCache.unix_time():
Expand Down

0 comments on commit d6cebc1

Please sign in to comment.