zoukankan      html  css  js  c++  java
  • Django中,使用redis作为缓存

    已有Django项目,在其中设置以redis为缓存。

    1、  安装django-redis:

    pip install django-redis

    2、  在settings里面配置cache设置:

    CACHES = {
        "default":{
            "BACKEND":"django_redis.cache.RedisCache",
            "LOCATION":"redis://127.0.0.1:6379/1",    # DB设为1
            "TIMEOUT":None,   # 永久缓存,默认300秒
            "OPTIONS":{
                "CLIENT_CLASS":"django_redis.client.DefaultClient",
                # "PASSWORD":"xxxxxx" # 可能需要密码
            }
        }
    }

    3、  设置好后可以在shell中测试一下:

    (1)       在终端中启动shell:

    python manage.py shell

    (2)       在shell中输入,并查看结果,验证可读写Cache:

    In [1]: from django.core.cache import cache

    In [2]: cache.set('mykey','haha,I get it!')

    Out[2]: True

    In [3]: cache.get('mykey')

    Out[3]: 'haha,I get it!'

    (3)       如果不能正常启动shell,可能是ipython版本过低,升级ipython即可:

    pip install ipython --upgrade

    4、  也可以新建test.py文件来验证,注意要导入settings并执行settings.configure():

    from django.conf import settings
    
    settings.configure()
    
    from django.core.cache import cache
    
    
    
    cache.set('key1','good day!')
    
    cache.set('key2','other day!')
    
    print(cache.get('key1'))
    
    print(cache.get('key2'))

    能正常显示如下即可:

    good day!

    other day!

  • 相关阅读:
    gulp 安装时一直提示缺少模块( Cannot find module 'gulp-load-plugins')
    webpack4.0入门以及使用
    重装系统(Win)
    单个雪碧图多个图像资源你该如何解决它们的定位?
    手机加载优化
    怎么下载google商店的扩展程序?
    ajax请求后台交互json示例
    scss
    Koala
    webpack-安装
  • 原文地址:https://www.cnblogs.com/djlbolgs/p/12803102.html
Copyright © 2011-2022 走看看