• Django中提供的6种缓存方式


    由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:

    缓存,缓存将一个某个views的返回值保存至内存或者memcache中,5分钟内再有人来访问时,则不再去执行view中的操作,而是直接从内存或者Redis中之前缓存的内容拿到,并返回。

    Django中提供了6种缓存方式:

    • 开发调试----什么都不做
    • 内存
    • 文件-----放到文件中
    • 数据库------放到数据库中
    • Memcache缓存(python-memcached模块)------memcache是一套分布式的高速缓存系统
    • Memcache缓存(pylibmc模块)---------memcache是一套分布式的高速缓存系统,用这个pylibmc模块去连接远程的Memcache机器。

    3种应用

    全局的

    视图函数

    局部模板

    开发调试,caches:高速缓存的意思。

     1 # 此为开始调试用,实际内部不做任何操作
     2     # 配置:
     3         CACHES = {
     4             'default': {
     5                 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',     # 引擎
     6                 'TIMEOUT': 300,                                               # 缓存超时时间(默认300,None表示永不过期,0表示立即过期)
     7                 'OPTIONS':{
     8                     'MAX_ENTRIES': 300,                                       # 最大缓存个数(默认300)
     9                     'CULL_FREQUENCY': 3,                                      # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3),剔除1/3
    10                 },
    11                 'KEY_PREFIX': '',                                             # 缓存key的前缀(默认空)
    12                 'VERSION': 1,                                                 # 缓存key的版本(默认1)
    13                 'KEY_FUNCTION' 函数名                                          # 生成key的函数(默认函数会生成为:【前缀:版本:key】)
    14             }
    15         }
    16  
    17  
    18     # 自定义key
    19     def default_key_func(key, key_prefix, version):
    20         """
    21         Default function to generate keys.
    22  
    23         Constructs the key used by all other methods. By default it prepends
    24         the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
    25         function with custom key making behavior.
    26         """
    27         return '%s:%s:%s' % (key_prefix, version, key)
    28  
    29     def get_key_func(key_func):
    30         """
    31         Function to decide which key function to use.
    32  
    33         Defaults to ``default_key_func``.
    34         """
    35         if key_func is not None:
    36             if callable(key_func):
    37                 return key_func
    38             else:
    39                 return import_string(key_func)
    40         return default_key_func

    2:,缓存将内容保存至内存的变量中

     1 # 此缓存将内容保存至内存的变量中
     2     # 配置:
     3         CACHES = {
     4             'default': {
     5                 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
     6                 'LOCATION': 'unique-snowflake',
     7             }
     8         }
     9  
    10     # 注:其他配置同开发调试版本

    3,缓存将内容保存至文件

     1 # 此缓存将内容保存至文件
     2     # 配置:
     3  
     4         CACHES = {
     5             'default': {
     6                 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
     7                 'LOCATION': '/var/tmp/django_cache',
     8             }
     9         }
    10     # 注:其他配置同开发调试版本

    4,缓存将内容保存至数据库

     1 # 此缓存将内容保存至数据库
     2  
     3     # 配置:
     4         CACHES = {
     5             'default': {
     6                 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
     7                 'LOCATION': 'my_cache_table', # 数据库表
     8             }
     9         }
    10  
    11     # 注:执行创建表命令 python manage.py createcachetable

    5,缓存使用python-memcached模块连接memcache

     1 # 此缓存使用python-memcached模块连接memcache
     2  
     3     CACHES = {
     4         'default': {
     5             'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
     6             'LOCATION': '127.0.0.1:11211',
     7         }
     8     }
     9  
    10     CACHES = {
    11         'default': {
    12             'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
    13             'LOCATION': 'unix:/tmp/memcached.sock',
    14         }
    15     }  
    16  
    17     CACHES = {
    18         'default': {
    19             'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
    20             'LOCATION': [
    21                 '172.19.26.240:11211',
    22                 '172.19.26.242:11211',
    23             ]
    24         }
    25     }<br><br>    CACHES = {<br>        'default': {<br>            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',<br>            'LOCATION': [<br>                ('172.19.26.240:11211',1),<br>                ('172.19.26.242:11211',15), 调权重<br>            ]<br>        }<br>    }

    6,缓存使用pylibmc模块连接memcache

     1 # 此缓存使用pylibmc模块连接memcache
     2      
     3     CACHES = {
     4         'default': {
     5             'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
     6             'LOCATION': '127.0.0.1:11211',
     7         }
     8     }
     9  
    10     CACHES = {
    11         'default': {
    12             'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
    13             'LOCATION': '/tmp/memcached.sock',
    14         }
    15     }  
    16  
    17     CACHES = {
    18         'default': {
    19             'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
    20             'LOCATION': [
    21                 '172.19.26.240:11211',
    22                 '172.19.26.242:11211',
    23             ]
    24         }
    25     }

    文件来做一个示例,即缓存内容保存到文件

    在setting中配置缓存

    1 # 此缓存将内容保存至文件
    2 # 配置:
    3 CACHES = {
    4     'default': {
    5         'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
    6         'LOCATION':os.path.join(BASE_DIR,'cache')
    7     }
    8 }
    View Code

    写cache视图函数

    1 def cache(request):
    2     import time
    3     ctime = time.time()
    4     return render(request,'cache.html',{'ctime':ctime})
    View Code

    写cache.html模板

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Title</title>
     6 </head>
     7 <body>
     8 <h1>{{ ctime }}</h1>
     9 <h1>{{ ctime }}</h1>
    10 <h1>{{ ctime }}</h1>
    11 </body>
    12 </html>
    View Code

    运行结果:每次刷新,时间都会发生变化

    cache视图函数

    给单独的views函数做上缓存,用装饰器实现。如果请求过来,先去缓存中去找,找不到的话,再执行函数。在这里设置了缓存为10秒钟有效,10秒之内刷页面,都是去缓存中拿数据,时间一直保持不变。10秒之后,时间才会更新。

    1 from django.views.decorators.cache import cache_page
    2 
    3 @cache_page(10)
    4 def cache(request):
    5     import time
    6     ctime = time.time()
    7     return render(request,'cache.html',{'ctime':ctime})
    View Code

    运行效果:10秒以后,时间才会发生变化。而且发现cache下的文件里面也有了缓存数据

    模板的某个局部做缓存

     1 {% load cache %}
     2 <!DOCTYPE html>
     3 <html lang="en">
     4 <head>
     5     <meta charset="UTF-8">
     6     <title>Title</title>
     7 </head>
     8 <body>
     9 <h1>{{ ctime }}</h1>
    10 <h1>{{ ctime }}</h1>
    11 {% cache 10 cuuuu %}
    12     <h1>{{ ctime }}</h1>
    13 {% endcache %}
    14 </body>
    15 </html>
    View Code

    全栈(全局)缓存,对整个网站的函数都做缓存

    用中间件实现,所有请求都经过中间件。

    在返回的最后一步才写到缓存中,因为在通过中间件的过程中,是可以修改views.py中的内容的。所以写到缓存中的应该是最终的版本。

    说明:

    实例:

    'django.middleware.cache.UpdateCacheMiddleware', 它里面没有process-request,只有process-response,只有离开的时候才会执行一次它,临走的时候更新一下。

    'django.middleware.cache.FetchFromCacheMiddleware', 它里面只有process_view,只有来的时候执行它,走的时候跟它没有关系。

    用户请求第一次来的时候,先到达中间件,跳过'django.middleware.cache.UpdateCacheMiddleware',一直往下执行,直到'django.middleware.cache.FetchFromCacheMiddleware',

    到它以后去缓存中找数据,如果没有的话,则继续往下到views.py中去找。

    返回数据时,跳过'django.middleware.cache.FetchFromCacheMiddleware',直到'django.middleware.cache.UpdateCacheMiddleware',把数据返回给用户,同时把数据放到缓存中。

    第二次请求到来的时候,到达到'django.middleware.cache.FetchFromCacheMiddleware',去缓存中找数据,发现有数据,则不用去views.py中取数据了,一直返回给客户。

  • 相关阅读:
    C# WPF全局捕获异常 防止程序崩溃闪退
    mysql数据库动态创建分区
    mysql增加修改主键_mysql怎么修改添加主键
    C#中@的用法总结(转)
    python OpenCV使用
    turtle --- 海龟绘图¶
    Python 常用趣味模块
    Eclipse中Ant的使用
    Eclipse中Ant的使用
    Thinking in java(五)
  • 原文地址:https://www.cnblogs.com/cerofang/p/8428858.html
Copyright © 2020-2023  润新知