Skip to content

Commit

Permalink
added SimpleCache
Browse files Browse the repository at this point in the history
  • Loading branch information
Smarties89 committed Jun 23, 2017
1 parent 1016729 commit 04e3356
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
39 changes: 39 additions & 0 deletions mps/simplecache.py
@@ -0,0 +1,39 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from time import time


class SimpleCache:
def __init__(self, timeout, storage=None):
if storage is None:
storage = {}

self._cache = storage
self._timeout = timeout

def _generate_key(self, args):
key = u""
for arg in args:
key += str(arg)
return key

def get(self, *args):
key = self._generate_key(args)
print key
cache = self._cache.get(key, None)
# Not in cache
if cache is None:
print(self._cache)
return None

# Not valid anymore after timeout
if cache['created'] + self._timeout < time():
return None

return cache['data']

def save(self, data, *args):
key = self._generate_key(args)
print(key)
self._cache[key] = {'data': data, 'created': time()}
12 changes: 12 additions & 0 deletions mps/test/test_simplecache.py
@@ -0,0 +1,12 @@
from time import sleep

from simplecache import SimpleCache

def test_simple_cache():
cache = SimpleCache(0.1)

assert cache.get("hamster") == None
cache.save("yumyum", "hamster")
assert cache.get("hamster") == "yumyum"
sleep(0.1)
assert cache.get("hamster") == None

0 comments on commit 04e3356

Please sign in to comment.