Django: how to cache a function
Question: 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 :)


Answer: 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):
        if not cache.get('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 = list(cur)
            dropList = simplejson.dumps({"dropList": dropList})
            cache.set('droplist', dropList, 600) # 10 minutes
        return HttpResponse(cache.get('droplist'), content_type="application/json")
    

