Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: how to cache a function

I have a web application that runs python in the back-end. When my page loads, a django function is called which runs a SQL query and that query takes about 15-20 seconds to run and return the response. And that happens every time the page loads and it would be very annoying for the user to wait 15-20 secs every time the page refreshes.

So I wanted to know if there is a way to cache the response from the query and store it somewhere in the browser when the page loads the first time. And whenever, the page refreshes afterwards, instead of running the query again, I would just get the data from browser's cache and so the page would load quicker.

This is the function that runs when the page loads

def populateDropdown(request):
    database = cx_Oracle.connect('username', 'password', 'host')
    cur = database.cursor()
    cur.execute("select distinct(item) from MY_TABLE")
    dropList = list(cur)
    dropList = simplejson.dumps({"dropList": dropList})
    return HttpResponse(dropList, content_type="application/json")

I can't seem to find an example on how to do this. I looked up Django's documentation on caching but it shows how to cache entire page not a specific function. It would be great if you can provide a simple example or link to a tutorial. Thanks :)

like image 562
Parth Bhoiwala Avatar asked Dec 14 '22 04:12

Parth Bhoiwala


1 Answers

You can the cache the result of the view that runs that query:

from django.views.decorators.cache import cache_page

@cache_page(600) # 10 minutes
def populateDropdown(request):
    ...

Or cache the expensive functions in the view which in your case is almost synonymous to caching the entire view:

from django.core.cache import cache

def populateDropdown(request):
    dropList = cache.get('droplist')
    if not dropList: # check if droplist has expired in cache
        database = cx_Oracle.connect('username', 'password', 'host')
        cur = database.cursor()
        cur.execute("select distinct(item) from MY_TABLE")
        dropList = simplejson.dumps({"dropList": list(cur)})
        cache.set('droplist', dropList, 600) # 10 minutes
    return HttpResponse(dropList, content_type="application/json")
like image 116
Moses Koledoye Avatar answered Dec 29 '22 17:12

Moses Koledoye