Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1016729
commit 04e3356
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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()} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |