Django study notes ------ cache

Configuring settings.py is the same as the configuration of the study notes sessions in the previous article

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', # Store in file cache
        'LOCATION': os.path.join(BASE_DIR,'cache'),
    }
}

views.py

@cache_page(5) # Put the cache function into the cache for 5s
def cache(request):
    import time
    cur_time = time.ctime()
    return render(request,'cache.html',{'time':cur_time})

cache.html

{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>{{ time }}</p><br/>
    <p>{{ time }}</p><br/>

{# Only cache the following time for 10s, the key is to take a random value and put it into the cache as a mark#}
    {% cache 10 key %}
    <p>{{ time }}</p><br/>
    {% endcache %}
</body>
</html>

If you want to cache globally, then add the following two sentences to the settings, and the location of the addition is shown in the figure

'django.middleware.cache.UpdateCacheMiddleware',    # UpdateCacheMiddleware 只有 process_reponse
'django.middleware.cache.FetchFromCacheMiddleware', # FetchFromCacheMiddleware class only has process_request, and go to cache to get





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325570657&siteId=291194637