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

  • 相关阅读:
    依赖单元测试开发
    今天晚上的遭遇
    设计,UML,测试驱动开发
    我是LIGHT的LP,今天由我代笔
    转贴一篇关于BitVector32的Blog
    看牙记
    调整过的书籍目录
    Queue和Stack的学习代码
    BitVector32结构学习
    Visual Studio 2008 在64位操作系统上调试代码的解决方式
  • 原文地址:https://www.cnblogs.com/icemonkey/p/10519526.html
Copyright © 2011-2022 走看看