Skip to content

Commit

Permalink
init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Matteo Senardi committed Oct 31, 2017
1 parent 806e272 commit ca6ddfb
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
15 changes: 15 additions & 0 deletions README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
===========
Django WEasy Cache
===========

Django WEasy Cache provides very simple cache decorator
it most useful for tasks involving <x> and also <y>. Typical usage
often looks like this::

from djangoweasycache import cache_for

@cache_for(cache_label='long_api_call', time=500)
def long_api_call(region_slug):
result = api.call(region_slug)
return result

45 changes: 45 additions & 0 deletions djangoweasycache/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import hashlib
import logging
from django.core.cache import caches

logger = logging.getLogger(__name__)


# stringify function args
def join_(*args):
rv = ""
for _string in args:
rv += ' ' + _string
return rv.lstrip()


# get cache key for storage
def cache_get_key(*args, **kwargs):
serialise = []
for arg in args:
serialise.append(str(arg))
for key, arg in kwargs.items():
serialise.append(str(key))
serialise.append(str(arg))
key = hashlib.md5("".join(serialise).encode('utf-8')).hexdigest()
return key


# decorator for caching functions
def cache_for(cache_label, time=None):
def decorator(fn):
def wrapper(*args, **kwargs):
cache = caches[cache_label]
key = cache_get_key(fn.__name__, *args, **kwargs)
result = cache.get(key)
if not result:
result = fn(*args, **kwargs)
cache.set(key, result, time)
logger.debug('Cache {} set {}'.format(cache_label, join_(*args)))
else:
logger.debug('Cache {} hit {}'.format(cache_label, join_(*args)))
return result

return wrapper

return decorator
9 changes: 9 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from distutils.core import setup

setup(
name='django-weasy-cache',
version='0.1dev',
packages=['djangoweasycache', ],
license='Creative Commons Attribution-Noncommercial-Share Alike license',
long_description=open('README.txt').read(),
)

0 comments on commit ca6ddfb

Please sign in to comment.