How to cache api using django memcached

1.7k Views Asked by At

1st time writing question on stackoverflow. I using python 2.7.11 and djnago 1.10.2. I created product models and saved 1000 products in my database.(postgrelsql) Actually, I used Django memcached but its not working.

Following steps:- 1. Added settings.py in caches backends.

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

Then "Creating the cache table." Database caching using Django Memcached:-

Django can store its cached data in your database. This works best if you’ve got a fast, well-indexed database server.To use a database table as your cache backend:

Set "BACKEND" to "django.core.cache.backends.memcached.MemcachedCache". Set "LOCATION" to "tablename", the name of the database table. This name can be whatever you want, as long as it’s a valid table name that’s not already being used in your database.

In this example, the cache table’s name is "product_cache_table:"
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'product_cache_table',
    }
}

Then "Creating the cache table." Before using the database cache, you must create the cache table with this command:

python manage.py createcachetable
Write business login. (product/views.py)

django.views.decorators.cache.cache_page()¶
def heavy_view(request):
    cache_key = 'product'
    cache_time = 18 # time to live in seconds
    result = Product.objects.all() # some calculations here
    for l in result:
        a = cache.set(cache_key, l, cache_time)

    c = cache.get(cache_key)

    return HttpResponse(c)

If i hit the url it saves all product in product_cache_table but only product_name is saved. when we get that data we only get product_name, but i want all the attributes in that Table. How to cached Api using Django Memcached. How workflow in Django Memcached. I have read doucmentation

2

There are 2 best solutions below

1
On

memcache is key-value. That means one key have one value.You are doing it as same key with different values.So that last value will be set there. Instead do like

cache.set(cache_key, list of products, cache_time)
0
On

I used django memcached in projects. It is working proper.