Django Cache with Memchaced
- Install Memcached on your system, if you are using Linux you can download it from:Memcached or you can install it using this command:
sudo apt-get update
sudo apt-get -y install memcached
-
If you are using Windows you can download it from:Memcached 64bit or Memcached 32bit
-
You can go to this site to learn how to install it on Windows:Memcached Windows
-
This is also the site explaining the cache, you can refer to it :Django Cache
-
Install pymemcache using this command:
pip install pymemcache
Add this to your
settings.py
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache",
"LOCATION": "127.0.0.1:11211",
}
}
Add this code also to your
settings.py
MIDDLEWARE = [
# ....
"django.middleware.cache.UpdateCacheMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.cache.FetchFromCacheMiddleware",
# ....
]
Add Cache settings to your
settings.py
CACHE_MIDDLEWARE_ALIAS = "default"
CACHE_MIDDLEWARE_SECONDS = 60 * 15 # 15 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = ""
from django.shortcuts import render
from django.views.decorators.cache import cache_page
# Create your views here.
@cache_page(60 * 15) # 15 minutes
def index(request):
return render(request, "cacheapp/index.html", {})
{% load cache %}
{% cache 500 sidebar request.user.username %}
.. sidebar for logged in users ..
{% endcache %}
from django.urls import path
from django.views.decorators.cache import cache_page
from . import views
app_name = "cacheapp"
urlpatterns = [
path("", cache_page(60 * 16)(views.index), name="index"),
]