Django per-view cache to database error

10 views
Skip to first unread message

Sanjay Ortiz

unread,
Mar 19, 2016, 8:41:32 AM3/19/16
to Django users

I was learning how to implement django cache framework in my simple web application.

I've used postgresql database and i've created my_cache_table. I tried using "per-view cache" technique but it doesn't work. No database entries at my_cache_table have been created.


#settings.py
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# Database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'shopprsense',
        'USER': 'shopprsense',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',
    }
}

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
        'TIMEOUT': 3600,
        'OPTIONS': {
            'MAX_ENTRIES': 1000
        }
    }
}

#urls.py
    urlpatterns = [
    url(r'^$', views.search_form),
    url(r'^s', cache_page(60 * 60)(views.search)),

]

#views.py
from .scraper import scrape
from django.views.decorators.cache import cache_page

def search_form(request):
    return render(request, 'scraper/search_form.html')

def search(request):
 q = request.GET["k"]
 ftitles, fprices, furls = scrape(q)
 context = {'ftitles': ftitles, 'fprices': fprices , 'furls': furls , 'q': q}
 return render(request, 'scraper/output.html', context)


This is how my web app works -

1.User enters keyword to search

2.Keyword is sent to the script "scrape.py" and processed and output is rendered and displayed in a page output.html.

My QUESTION -

  • It would be great if i could cache the search view response so that a hefty process that happens in the search view can be avoided.

  • So when user searches for the same keyword that has been cached, the response can be displayed from cache avoiding the process.

  • I tried using per-view caching in urls but it doesn't work

  • Please point out what am i missing here .

Any help is appreciated.

Reply all
Reply to author
Forward
0 new messages