#example
from django.core.cache import cache
cache.set('hello_19374', 'some value here') # will set the key hello_19374 to 'some value here'
cache.set('hello_xfhh', 'some value here') # etc
cache.set('19374hello', 'some value here') # etc
cache.set('alal_hello_19374', 'some value here') # etc
cache.set('lalahellohdgf', 'some value here') # etc
print cache.filter('hello%') # will show all keys beginning with 'hello'
print cache.filter('%%') # will show all keys
print cache.filter('%hello') # will show all keys ending with 'hello'
print cache.filter('%hello%') # will show all keys containing 'hello'
cache.clean() # will delete any cache entries which have past their expiry
#app/settings.py
CACHE_BACKEND = 'app.cache://cache_table_name_goes_here'
#app/cache.py
"Database cache backend."
from django.core.cache.backends.db import CacheClass as _CacheClass
from django.core.cache.backends.base import BaseCache
from django.db import connection, transaction, DatabaseError
import base64, time
from datetime import datetime
try:
import cPickle as pickle
except ImportError:
import pickle
# Import the threading and time
import threading
def RoutineCacheClean():
# Import the cache
from django.core.cache import cache
# Loop forever!
while True:
# Clean it!
try:
cache.clean()
except:
pass
# Clean every 3 minutes
time.sleep(60*3)
def StartCacheClean():
# Create the new thread
t = threading.Thread(
target = RoutineCacheClean
)
# Set the thread daemon flag to true
t.setDaemon(True)
# Start the thread
t.start()
class CacheClass ( _CacheClass ):
def filter(self, key, default=None):
lx={}
cursor = connection.cursor()
cursor.execute("SELECT cache_key, value, expires FROM %s WHERE cache_key LIKE %%s" % self._table, [key])
for row in cursor.fetchall():
if row is not None:
now = datetime.now()
if row[2] < now:
cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [row[0]])
transaction.commit_unless_managed()
else:
value = connection.ops.process_clob(row[1])
lx[row[0]]=pickle.loads(base64.decodestring(value))
return lx
def clean(self):
cursor = connection.cursor()
now = datetime.now().replace(microsecond=0)
cursor.execute("DELETE FROM %s WHERE expires < %%s" % self._table, [str(now)])
transaction.commit_unless_managed()
StartCacheClean()
Comments