1

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

hmm but in your code how will i get cal from my db which is currently default now
@YashBontala just call cache.get('cal')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.