简体   繁体   English

如何在Django中缓存视图

[英]How to cache views in django

I am currently using django and I'm attempting to cache my view like so 我目前正在使用django,并且尝试像这样缓存我的视图

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def index(request):
   # This method takes time to run, which is why I need to cache this view
   a_method_that_preforms_heavy_db_transactions()

   context_dict={'Models': Model.objects.all()} 
   return render(request, 'webapp/index.html', context_dict)

I have a_method_that_preforms_heavy_db_transactions() In just to test the loading time to see if it cached the view but the loading time time doesn't change when its supposed to be "cached" and I'm unsure why this is my settings.py 我有一个a_method_that_preforms_heavy_db_transactions()只是为了测试加载时间以查看它是否缓存了视图,但是当它应该被“缓存”时,加载时间不会改变,我不确定为什么这是我的settings.py

 CACHES = {
    'default': {
    'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
    'LOCATION': 'My_computers_ip_address:11211',
   }
}

You'll need to add a caching service , eg Memcached 您需要添加一个caching service ,例如Memcached

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211/A_ROUTE_WITH_A_HEAVY_TRANSACTION',
    }
}

You'll find everything you need here: 您会在这里找到所需的一切:

https://docs.djangoproject.com/en/stable/topics/cache/ https://docs.djangoproject.com/en/stable/topics/cache/

Have you set caching up ? 您是否设置了缓存 You need to define CACHES in your settings.py file. 您需要在settings.py文件中定义CACHES You can use memcached, Redis, your database or a file system. 您可以使用memcached,Redis,数据库或文件系统。 The simplest setup is with local memory as it doesn't require any external services: 最简单的设置是使用本地内存,因为它不需要任何外部服务:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM