zoukankan      html  css  js  c++  java
  • django中缓存配置

    # ======缓存配置======
    CACHES = {
        ## 虚拟缓存,开发调试版本,此为开始调试用,实际内部不做任何操作
        # 'default': {
        #  'BACKEND': 'django.core.cache.backends.dummy.DummyCache',  # 引擎
        #  'TIMEOUT': 300, # 缓存超时时间(默认300秒,None表示永不过期,0表示立即过期)
        #  'OPTIONS':{
        #       'MAX_ENTRIES': 300,# 最大缓存个数(默认300)
        #       'CULL_FREQUENCY': 3,# 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3),3:表示1/3
        #  },
        # #这边只的是缓存的key:p1:1:func_name
        #     'KEY_PREFIX': 'p1',# 缓存key的前缀(默认空)
        #     'VERSION': 1, # 缓存key的版本(默认1)
        #     'KEY_FUNCTION':"func_name"# 生成key的函数(默认函数会生成为:【前缀:版本:key】)
        #},
      # # redis缓存 "default": { # redis "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://10.255.0.250:6379/2", # "LOCATION": "redis://127.0.0.1:6379/2", # 其他配置 "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", 'CULL_FREQUENCY': 3, # 用于 compression "COMPRESS_MIN_LEN": 10, }, 'TIMEOUT': 18000, # 5hours 默认是300秒 },
      # # memcache缓存 'memcache': { # memcache 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', # 其他配置 # 默认的缓存有效时间,以秒计. 默认值是 300 秒 'TIMEOUT': 18000, # 5 hours 'options': { # 用于 简单缓存 及 数据库缓存 后端, 缓存的最大条目数(超出该数旧的缓存会被清除,默认值是 300). 'MAX_ENTRIES': 1024, # 当达到缓存的最大条目数时要保留的精选条目比率 实际被保存的是 1/cull_percentage, # 因此设置 cull_percentage=3 就会保存精选的 1/3 条目上,其余的条目则被删除 # 如果将 cull_percentage 设置为 0 则意味着当达到缓存的最大条目数时整个缓存都被清除 'CULL_FREQUENCY': 3, } }, # #文件系统缓存 'file_cache': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(BASE_DIR, 'files_cache'),# 缓存存放路径 # #其他配置 'TIMEOUT': 18000, # 5 hours 'OPTIONS': { 'MAX_ENTRIES': 10000, 'CULL_FREQUENCY': 3, } }, # # 本地内存 # 'default': { # 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', # 'LOCATION': 'unique-snowflake', #这边必须设置一个值,这个值是唯一的 # # 其他配置 # 'options': { # 'MAX_ENTRIES': 1024, # } # },
       # # 缓存存放于数据库中
       #'default':{
       #   'BACKEND':'django.core.cache.backends.db.DatabaseCache',
       #   'LOCATION':'my_cache_table',#设置一个数据库存放缓存的表名
       #},
    }

     支持集群、负载均衡

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': [
                '172.19.26.240:11211',
                '172.19.26.242:11211',
               #设置权重
               #('172.19.26.240:11211',10),
               #('172.19.26.242:11211',20),
            ]   
        }
        #其他的配置和开发调试版本一样
    }
    

     缓存应用

    单视图缓存

    数据库:

    class Book(models.Model):
        name=models.CharField(max_length=32)
        price=models.DecimalField(max_digits=6,decimal_places=1)
    

     视图(方式一):

    from django.views.decorators.cache import cache_page
    import time
    from .models import *
    
    @cache_page(60 * 15)#超时时间为15分钟
    def index(request):
    
     t=time.time()#获取当前时间
     bookList=Book.objects.all()
     return render(request,"index.html",locals())
    

     视图(方式二):

    from django.views.decorators.cache import cache_page
            urlpatterns = [
                url(r'^myIndex/$', cache_page(60 * 15)(index)),
            ]
    

    模板:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3>当前时间:-----{{ t }}</h3>
    
    <ul>
        {% for book in bookList %}
           <li>{{ book.name }}--------->{{ book.price }}$</li>
        {% endfor %}
    </ul>
    
    </body>
    </html>
    

    全站使用缓存

      既然是全站缓存,当然要使用Django中的中间件.

      用户的请求通过中间件,经过一系列的认证等操作,如果请求的内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户

      当返回给用户之前,判断缓存中是否已经存在,如果不存在,则UpdateCacheMiddleware会将缓存保存至Django的缓存之中,以实现全站缓存

    ##缓存整个站点,是最简单的缓存方法
    ##在 MIDDLEWARE_CLASSES 中加入 “update” 和 “fetch” 中间件
    MIDDLEWARE_CLASSES = (
        ‘django.middleware.cache.UpdateCacheMiddleware’, #第一
        'django.middleware.common.CommonMiddleware',
        ‘django.middleware.cache.FetchFromCacheMiddleware’, #最后
    )
    ##“update” 必须配置在第一个
    ##“fetch” 必须配置在最后一个
    

     视图:

    from django.views.decorators.cache import cache_page
    import time
    from .models import *
    
    
    def index(request):
         t=time.time()      #获取当前时间
         bookList=Book.objects.all()
         return render(request,"index.html",locals())
    def foo(request):
        t=time.time()      #获取当前时间
        return HttpResponse("HELLO:"+str(t))
    

     模板:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3 style="color: green">当前时间:-----{{ t }}</h3>
    
    <ul>
        {% for book in bookList %}
           <li>{{ book.name }}--------->{{ book.price }}$</li>
        {% endfor %}
    </ul>
    
    </body>
    </html>
    

    其余代码不变,刷新浏览器是10秒,页面上的时间变化一次,这样就实现了全站缓存 

    局部视图缓存

    例子,刷新页面时,整个网页有一部分实现缓存

    视图:

    from django.views.decorators.cache import cache_page
    import time
    from .models import *
    
    def index(request):
         t=time.time()      #获取当前时间
         bookList=Book.objects.all()
         return render(request,"index.html",locals())
    

     模板:

    {% load cache %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
     <h3 style="color: green">不缓存:-----{{ t }}</h3>
    
    {% cache 2 'name' %}
     <h3>缓存:-----:{{ t }}</h3>
    {% endcache %}
    
    </body>
    </html>
    
    {% cache 缓存时间 缓存的key %}{% endcache %}
    
  • 相关阅读:
    MongoDB ObjectId
    MongoDB固定集合
    MongoDB 正则表达式
    MongoDB Map Reduce
    MongoDB操作
    VIM跳到指定行
    linux之echo命令
    rpm and yum commands
    CentOS 7 下的软件安装建议
    apt系统中sources.list文件的解析
  • 原文地址:https://www.cnblogs.com/konglingxi/p/9438061.html
Copyright © 2011-2022 走看看