1. Hynek Cernoch
  2. django-keyedcache

Commits

Hynek Cernoch  committed 49f24c7

Added documentation. Closes #8.

  • Participants
  • Parent commits 2383c8a
  • Branches default

Comments (0)

Files changed (3)

File docs/about.rst

View file
 
 Django-keyedcache provides a simplified, speedy way to manage caching in Django apps.
 
-Cache statistics, cached keys and deleting the cache can be accessed by running the dev server in the test_app directory and going to `settings <http://127.0.0.1:8000/cache/>`_ ::
+Example
+-------
+The most frequent usage:
+
+    import keyedcache import cache_set, cache_get, NotCachedError
+    import keyedcache
+
+    # ... create come object
+    # cache it
+    cache_set("product", 123, value=product)
+    cache_set("product", 123, value=product, length=3600)  # different timeout
+    # ... delete it
+    # get it
+    try:
+        value = cache_get("product", 123)
+    except NotCachedError:
+        value = None
+
+    # the syntax "parameter=var" does exactly the same as the previous:
+    try:
+        value = cache_get(product=123)
+    ....
+
+    # optional deleting
+    keyedcache.cache_delete('some.temporary.secret')
+
+The reference documentation for these functions is their docs strings.
+
+Advanced examples
+-----------------
+More rare usage:
+
+    # it is better sometimes to call the internal function `cache_key` to
+    # combine complicated parameters to one key used multiple times0.
+    cachekey = keyedcache.cache_key('SHIP_company', \
+            weight=str(weight), country=country.code, zipcode=zipcode)
+    try:
+        value = cache_get(cachekey)
+    except NotCachedError:
+        value = None
+    if value == None:
+        value = ...long running function...
+        cache_set(cachekey, value=value)
+        log.info('message %s', cachekey)
+
+    ...
+
+    # Mixin - for models.py - simplified caching for some model
+    class MyNewModel(models.Model, keyedcache.CachedObjectMixin):
+        # some Fields...
+
+        # we can easy cache saving of all objects without writing the keys
+        def save(self):
+            # ... do somehting
+            self.cache_delete()
+            super(MyNewModel, self).save()
+            self.cache_set()
+            return self
+
+Additional first-level caching
+------------------------------
+
+If you want first to cache the values temporary in the memory during one request
+before the normal django cache.
+
+    from keyedcache import threaded
+    threaded.start_listening()
+
+This should be safe also with multithreading.
+
+
+Web interface
+-------------
+
+Cache statistics, cached keys and deleting the cache can be accessed by running the dev
+server in the test_app directory and going to `settings <http://127.0.0.1:8000/cache/>`_ ::
+
+(Urls of in keyedcache are usually mapped to "/cache" by the main application.)
+The web intergace is for debugging purposes and usage with debug server.
+If the server is running in production with multiple worker processes,
+the information provided by the web interface is incomplete. The access
+to the web interface requires "is_staff" permissions.

File keyedcache/__init__.py

View file
-"""A full cache system written on top of Django's rudimentary one."""
+"""A full cache system written on top of Django's rudimentary one.
+
+Frequently used functions are:
+    cache_set(*keys, **kwargs)
+    cache_get(*keys, **kwargs)
+    cache_delete(*keys, **kwargs)
+keys.. parameters of general type which are convertable to string or hashable unambiguously.
+The keys can be of any general type which is convertable to string unambiguously or hashable.
+Every unknown kwarg is interpreted like two aditional keys: (key, val).
+Example:
+    cache_set('product', 123, value=product)
+    # is the same as
+    cache_set('product::123', value=product)
+
+More info below about parameters.
+"""
 
 from django.conf import settings
 from django.core.cache import cache
 
 log = logging.getLogger('keyedcache')
 
+# The debugging variable CACHED_KEYS is exact only with the the Django
+# debugging server (or any single worker process server) and without restarting
+# the server between restarts of the main cache (memcached).
+# Keys in CACHED_KEYS variable never expire and can eat much memory on long
+# running servers. Currently it is not confirmed in Satchmo.
+# If more worker processes are used, the reported values of the following three
+# variables can skip randomly upwards downwards.
 CACHED_KEYS = {}
 CACHE_CALLS = 0
 CACHE_HITS = 0
+
 KEY_DELIM = "::"
 REQUEST_CACHE = {'enabled' : False}
 try:
     pass
 
 def cache_delete(*keys, **kwargs):
+    """
+    Deletes the object identified by all ``keys`` from the cache.
+
+    keys:
+        Parameters of general type which are convertable to string or hashable
+        unambiguously.
+    kwargs:
+        children:
+            If it is True more objects starting with these keys are deleted.
+        other kwargs:
+            Unknown key=val is interpreted like two aditional keys: (key, val)
+
+    If no keys are present, all cached objects are to be deleted.
+    Deleting multiple multiple or all objects is usually not complete if the
+    project is running with multiple worker processes.
+    (It is reliable e.g. with a development server.)
+    """
     removed = []
     if cache_enabled():
         global CACHED_KEYS
         log.debug('cache_delete')
-        children = kwargs.pop('children',False)
+        children = kwargs.pop('children', False)
 
         if (keys or kwargs):
             key = cache_key(*keys, **kwargs)
 
 
 def cache_get(*keys, **kwargs):
+    """
+    Gets the object identified by all ``keys`` from the cache.
+
+    kwargs:
+        default:
+            Default value used if the object is not in the cache. If the object
+            is not found and ``default`` is not set or is None, the exception
+            ``NotCachedError`` is raised with the attribute ``.key = keys``.
+        other kwargs:
+            Unknown key=val is interpreted like two aditional keys: (key, val)
+    """
     if kwargs.has_key('default'):
         default_value = kwargs.pop('default')
         use_default = True
 
 
 def cache_set(*keys, **kwargs):
-    """Set an object into the cache."""
+    """Set the object identified by all ``keys`` into the cache.
+
+    kwargs:
+        value:
+            The object to be cached.
+        length:
+            Timeout for the object. Default is CACHE_TIMEOUT.
+        skiplog:
+            If it is True the call is never logged. Default is False.
+        other kwargs:
+            Unknown key=val is interpreted like two aditional keys: (key, val)
+    """
     if cache_enabled():
         global CACHED_KEYS, REQUEST_CACHE
         obj = kwargs.pop('value')

File keyedcache/models.py

View file
 log = logging.getLogger('keyedcache')
 
 class CachedObjectMixin(object):
-    """Provides basic object keyedcache for any objects using this as a mixin."""
+    """Provides basic object keyedcache for any objects using this as a mixin.
+
+    The class name of the object should be unambiguous.
+    """
 
     def cache_delete(self, *args, **kwargs):
         key = self.cache_key(*args, **kwargs)
         
     def is_cached(self, *args, **kwargs):
         return keyedcache.is_cached(self.cache_key(*args, **kwargs))
-
+        
 
 # Unused functions find_by_id, find_by_key, find_by_slug are coming from
 # Satchmo but are currently unused also there.