zoukankan      html  css  js  c++  java
  • luffy——django中使用redis

    方案一:通用方案

    luffyapiutils edis_pool.py

    import redis
    
    POOL=redis.ConnectionPool(host='127.0.0.1', port=6379,max_connections=100)

    luffyapiappsuserviews.py

    from utils.redis_pool import POOL
    import redis
    def test_redis(request):
        conn=redis.Redis(connection_pool=POOL)
        age=str(conn.get('age'),encoding='utf-8')
        return HttpResponse('人的年龄从redis中取出来:%s'%age)

    luffyapiappsuserurls.py

    path('test_redis/',views.test_redis)

    测试地址:

    http://127.0.0.1:8000/user/test_redis/

    方案二:(推荐方案)django提供的方案

    执行命令

    pip3 install django-redis  #注意如果django版本过低就会直接把django升级为最新版本,可以安装好此模块后再重新把django版本换回来

    配置文件

    luffyapisettingsdev.py

    # redis的配置
    #以后django的缓存,用的就是redis,很方便使用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": "123",
            }
        }
    }

    luffyapiappsuserviews.py

    from django_redis import get_redis_connection
    def test_django_redis(request):
        # 从连接池中拿到连接
        conn=get_redis_connection()
    
        age = str(conn.get('age'), encoding='utf-8')
    
        from django.core.cache import cache
        cache.set('name','lili',4)  # 往缓存中放key和value,其实放到了redis中了.4指的是过期时间
       catch.get('name')#取
    
        cache.set('xxx',test_redis)#可以放对象(函数也是对象)
        return HttpResponse('人的年龄是:%s' % age)

    luffyapiappsuserurls.py

    path('test_django_redis/',views.test_django_redis)

    测试地址:

    http://127.0.0.1:8000/user/test_django_redis/
  • 相关阅读:
    struts2(2.0.x到2.1.2版本)的核心和工作原理(转)
    关于Struts2通配符无效的说明
    contOS 网络配置
    INFORMATICA 开发规范
    Python tricks(1) -- 动态定义一个新变量
    MySQL connector c++使用笔记
    python使用set来去重碰到TypeError: unhashable type
    Redis 资料整理
    Ruby 安装和gem配置
    爱读书的犹太人
  • 原文地址:https://www.cnblogs.com/guojieying/p/14278681.html
Copyright © 2011-2022 走看看