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': 'dbname',
'USER': 'username',
'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.
Found the solution, i'm posting it coz it might help someone.
The problem is i forgot to import cache decorators in url.py file I wonder why runserver didn't throw me an error before. Well today it did throw me the error.
NameError: name 'cache_page' is not defined
After updating my urls.py per-view caching worked super fine .
from django.views.decorators.cache import cache_page
Something i learnt - Restart your cmd and then restart your server.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.