Django global data for streams

I have a shared global data object on my single-processor, multi-threaded django server - an object that is often used, but is infrequently evaluated. The calculation takes a lot of time, so I want to share the results.

I thought this would work with django LocalMemCache for this simple data. Oddly enough, it works for multiple ajax calls when loading a single page, but for some reason, when I reload the page in my browser, the cache is empty again.

What am I doing wrong?

Is there a better way? Will a global variable be just as effective if I control write access with a thread lock?

Here is basically what I am doing:

from threading import Lock
from django.core.cache import get_cache

my_lock = Lock()
cache = get_cache('default')

def get_global_data():
    my_lock.acquire()
    try:
        cached_data = cache.get('data')
        if not cached_data:
            cached_data = big_function_to_calculate_data()
            cache.set('data', cached_data)
    finally:
        my_lock.release()
    return cached_data

# settings.py defines my django LocMemCache as:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'my_server'
    }
}

Edit

( ), (GET, POST) .. POST , GET ( ) .

+4
1

. , LocMemCache.

# run python manage.py createcachetable

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

, (GET, POST) .. POST GET .

+3

Source: https://habr.com/ru/post/1540236/


All Articles