how to store variables in django cache db

Viewed 203

i am making a cache db using the django cache module i configured it in my settings.py like this

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

so in my something.py file example

def function():
   log=cache['default']
   log["cal"]+=1

can i do this so that a variable like cal would be formed and it would increase every time i call that function

1 Answers

First, you need to make sure the cache table exists in your database. Django provides a management command for this:

python3 manage.py createcachetable

Now to increment cal:

# a convenience import for the default cache
from django.core.cache import cache

def increment_cal():
    cal = cache.get_or_set('cal', 0)
    cal += 1
    cache.set('cal', cal)

There is only one problem, this code has a race condition. If multiple threads try to increment cal at the same time, you can get inaccurate results.

To fix this, you will need a thread lock:

import threading
from django.core.cache import cache

cal_lock = threading.Lock()

def increment_cal():
    with cal_lock:
        cal = cache.get_or_set('cal', 0)
        cal += 1
        cache.set('cal', cal)

Note that this only solves race conditions between threads. If you have multiple processes trying to increment cal, you will need to use a multiprocessing lock instead.

Related