zoukankan      html  css  js  c++  java
  • Python-Django使用MemcachedCache缓存

    最近工作中使用到缓存,简单记录之...

    关于django的几种缓存方式,就不在做介绍了,网上一搜一大把:1.8.2官方文档, Django 缓存,Python菜鸟之路:django缓存

    学习了之后,选择的是,MemcachedCache,此缓存使用python-memcached模块连接memcache。

    关于Python-memcached的安装以及介绍就不在做介绍,可查看文章:python3之memcached,python---Memcached

    1)在Django的settings中设置缓存

    CACHES = {
    'default': {
    'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
    'LOCATION': ,'127.0.0.1:11211', # 可以为远程地址和端口,可以设置多个ip
    'TIMEOUT': 86400, # 1 day,设置成0缓存将失效
    'OPTIONS': {
    'MAX_ENTRIES': 1000, # 高速缓存允许的最大条目数,超出这个数则旧值将被删除. 这个参数默认是300.
    'CULL_FREQUENCY': 3, # 当达到MAX_ENTRIES 的时候,被删除的条目比率。 实际比率是 1 / CULL_FREQUENCY,默认是3
    }
    }
    }
    2)业务代码:

    #coding=utf-8
    def key_hash(value):
    """hash缓存key,防止过长"""
    import hashlib
    return '%s' % hashlib.md5(value).hexdigest()


    def cache(num1, num2):
    """
    :param num1: 获取或者设置cache的标识
    :param num2:获取或者设置cache的标识
    :return: 缓存dict
    """
    from django.core.cache import cache
    import logging
    log = logging.getLogger(__name__) # 日志
    # 去重并排序,增加缓存命中率
    cache_key = 'num1={num1}&num2={num2}'.format(num1=num1, num2=num2)
    cache_key = key_hash(cache_key)

    # in cache, return cache
    if cache.get(cache_key):
    log.debug('cache %s hitting ' % cache_key)
    return cache.get(cache_key)

    # not in cache, get result and set cache
    ret = None
    # TODO do something get result
    ret = 'something'
    cache.set(cache_key, ret, 60 * 60 * 24) # 一天过期
    return ret

    ---------------------
    作者:微光刺眼丶
    来源:CSDN
    原文:https://blog.csdn.net/weixin_40475396/article/details/80351578?utm_source=copy
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    67. Add Binary
    66. Plus One
    64. Minimum Path Sum
    63. Unique Paths II
    How to skip all the wizard pages and go directly to the installation process?
    Inno Setup打包之先卸载再安装
    How to change the header background color of a QTableView
    Openstack object list 一次最多有一万个 object
    Openstack 的 Log 在 /var/log/syslog 里 【Ubuntu】
    Git 分支
  • 原文地址:https://www.cnblogs.com/ExMan/p/9777909.html
Copyright © 2011-2022 走看看