[Answered ]-How to store variables in django cache db

1👍

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.

Leave a comment