zoukankan      html  css  js  c++  java
  • Django Redis存储session会话

     

    通常redis都是用来保存session、短信验证码、图片验证码等数据。

    在django上使用redis,先要安装一个包:

    pip install django-redis==4.8.0(我用的django是1.11.1版本)

    在settings上配置:

    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://192.168.8.102:6379/0",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
            }
        },
        "session": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://192.168.8.102:6379/1",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
            }
        },
        "sms_codes": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://192.168.8.102:6379/2",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
            }
        }
    }
    
    # 保存 session数据到 Redis中
    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
    SESSION_CACHE_ALIAS = "session"

    在视图中使用:

    # 在redis上查看存储的会话

    # 2) ":1:django.contrib.sessions.cachehdrgn4pbtnylv23241089a4ajfkh8f4f"
    import json
    from django_redis import get_redis_connection

    con = get_redis_connection("sms_codes") #con就是StrictRedis类型,default对应settings.py中CACHES中设置的sms_codes

    # dict序列化字符串存储到redis
    name = "zhangsan"
    val = {"is_login": "True", "username": "zhangsan"}
    res = con.set(name, json.dumps(val))

    # 从redis取数据
    # res = eval(con.get("zhangsan").decode("utf-8"))
    res =con.get(name)
    print(res)


    cp:https://blog.csdn.net/houyanhua1/article/details/84992717

    https://blog.csdn.net/houyanhua1/article/details/85052846

    https://www.cnblogs.com/yuanchenqi/articles/5716193.html

    https://www.jianshu.com/p/2639549bedc8

  • 相关阅读:
    对象无法注册到Spring容器中,手动从spring容器中拿到我们需要的对象
    sping,springMVC @Component 注解的对象都是单例模式,变量不能全局
    java读取项目路径下的中文文件乱码问题
    springboot集成mongoDB 异常认证
    观察者模式
    MongoDB学习笔记03
    MongoDB学习笔记02
    ajax参数中出现空格
    web并发模型
    MongoDB shell
  • 原文地址:https://www.cnblogs.com/icemonkey/p/10519526.html
Copyright © 2011-2022 走看看