python - Django: how to cache a function -


i have web application runs python in back-end. when page loads, django function called runs sql query , query takes 15-20 seconds run , return response. , happens every time page loads , annoying user wait 15-20 secs every time page refreshes.

so wanted know if there way cache response query , store somewhere in browser when page loads first time. , whenever, page refreshes afterwards, instead of running query again, data browser's cache , page load quicker.

this function runs when page loads

def populatedropdown(request):     database = cx_oracle.connect('username', 'password', 'host')     cur = database.cursor()     cur.execute("select distinct(item) my_table")     droplist = list(cur)     droplist = simplejson.dumps({"droplist": droplist})     return httpresponse(droplist, content_type="application/json") 

i can't seem find example on how this. looked django's documentation on caching shows how cache entire page not specific function. great if can provide simple example or link tutorial. :)

you can cache result of view runs query:

from django.views.decorators.cache import cache_page  @cache_page(600) # 10 minutes def populatedropdown(request):     ... 

or cache expensive functions in view in case synonymous caching 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) 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") 

Comments