• 缓存实例


    由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:缓存,缓存将一个某个views的返回值保存至内存或者memcache中,

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

    5种配置

    (1)、开发调试版本:

     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)
    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
    View Code

    (2)、内存版本

    # 此缓存将内容保存至内存的变量中
        # 配置:
            CACHES = {
                'default': {
                    'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
                    'LOCATION': 'unique-snowflake',
                }
            }
    
        # 注:其他配置同开发调试版本
    View Code

    (3)、文件

    # 此缓存将内容保存至文件
        # 配置:
    
            CACHES = {
                'default': {
                    'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
                    'LOCATION': '/var/tmp/django_cache',
                }
            }
        # 注:其他配置同开发调试版本
    View Code

    (4)、数据库

    # 此缓存将内容保存至数据库
    
        # 配置:
            CACHES = {
                'default': {
                    'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
                    'LOCATION': 'my_cache_table', # 数据库表
                }
            }
    
        # 注:执行创建表命令 python manage.py createcachetable
    View Code

    (5)、Memcache缓存(python-memcached模块)

    # 此缓存使用python-memcached模块连接memcache
    
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
                'LOCATION': '127.0.0.1:11211',
            }
        }
    
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
                'LOCATION': 'unix:/tmp/memcached.sock',
            }
        }   
    
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
                'LOCATION': [
                    '172.19.26.240:11211',
                    '172.19.26.242:11211',
                ]
            }
        }
    View Code

    (6)、Memcache缓存(pylibmc模块)

    # 此缓存使用pylibmc模块连接memcache
        
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
                'LOCATION': '127.0.0.1:11211',
            }
        }
    
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
                'LOCATION': '/tmp/memcached.sock',
            }
        }   
    
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
                'LOCATION': [
                    '172.19.26.240:11211',
                    '172.19.26.242:11211',
                ]
            }
        }
    View Code

    (7)Redis缓存(依赖:pip3 install django-redis)

    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "CONNECTION_POOL_KWARGS": {"max_connections": 100}
                # "PASSWORD": "密码",
            }
        }
    }
    View Code
    from django_redis import get_redis_connection
    conn = get_redis_connection("default")
    视图中链接并操作

    3种应用:
    全局

     1 使用中间件,经过一系列的认证等操作,如果内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户,当返回给用户之前,判断缓存中是否已经存在,如果不存在则UpdateCacheMiddleware会将缓存保存至缓存,从而实现全站缓存
     2 
     3     MIDDLEWARE = [
     4         'django.middleware.cache.UpdateCacheMiddleware',
     5         # 其他中间件...
     6         'django.middleware.cache.FetchFromCacheMiddleware',
     7     ]
     8 
     9     CACHE_MIDDLEWARE_ALIAS = ""
    10     CACHE_MIDDLEWARE_SECONDS = ""
    11     CACHE_MIDDLEWARE_KEY_PREFIX = ""
    View Code

    视图函数

    方式一:
            from django.views.decorators.cache import cache_page
    
            @cache_page(60 * 15)
            def my_view(request):
                ...
    
        方式二:
            from django.views.decorators.cache import cache_page
    
            urlpatterns = [
                url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
            ]
    View Code

    模板

    1 a. 引入TemplateTag
    2 
    3         {% load cache %}
    4 
    5     b. 使用缓存
    6 
    7         {% cache 5000 缓存key %}
    8             缓存内容
    9         {% endcache %}
    View Code

     

  • 相关阅读:
    python函数
    python数据类型补充,copy知识点及文件的操作
    python数据类型
    python介绍
    Linux基础2-2 基础文件管理命令
    Linux基础2-1 根文件系统分析
    Linux基础1-3 命令使用帮助的获取
    Linux基础1-2 ls、cd、date、clock、cal、echo、printf命令使用简介
    Linux基础1-1
    fastDFS环境搭建
  • 原文地址:https://www.cnblogs.com/qiangayz/p/9000305.html
Copyright © 2020-2023  润新知