django-redis 使用

Django-redis 使用

  • 安装 django-redis

    pip install django-redis
    
  • 配置信息

    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379/8",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "CONNECTION_POOL_KWARGS": {"max_connections": 100},
                # "PASSWORD": "密码",
      		  'CONNECTION_POOL_KWARGS': {'decode_responses': True}, # 添加这一行,数据正常返回,否则将以bytes返回
            }
        }
    }
    
  • 使用 views.py

    from django.core.cache import cache
    from rest_framework.views import APIView
    from rest_response import Response
    
    class OrderViews(APIView):
        # 读取缓存信息
        def get(self,request):
            tmp = cache.get('key')
            return Response({
                "res":200,
                "msg":"",
                "data":tmp
            })
        # 设置缓存信息
        def post(self,request):
            # 设置成功返回True,否则返回False
            tmp = cache.set('key','value',10)
            return Response({
                "res":200,
                "msg":"设置成功"
            })
    
  • 使用views.py

    from django.core.cache import cache
    from rest_framework.views import APIView
    from rest_response import Response
    from django_redis  import  get_redis_connection
    # 购物车
    class CartViews(APIView):
        # 初始化参数
        def __init__(self):
            self.conn = get_redis_connection('default')
            
        
        # 设置缓存信息
        def post(self,request):
            tmp = self.conn.hset('cart_1',2,{'name':'oppo30pro','price':5999,'count':1})
    		if tmp:
                return Response({
                    "res":200,
                    "msg":"缓存设置成功"
                })
            return Response({
                "res":201,
                "msg":"缓存设置失败"
            })
        
        
        
        # 读取缓存
        def get(self,request):
            data = self.conn.hgetall('cart_1')
            return Response({
                "res":201,
                "msg":"",
                "data":data
            })
    
  • url.py

    from django.urls import path,include
    from . import views
    urlpatterns = [
        path('cache/',views.OrderView.as_view()),
    ]
    
  • 关于hash还有其他获取值的方式

    • hgetall(name) 取出name对应hash的所有键值
    • hlen(name)获取对应的hash中键值对的个数
    • hkeys(name)返回所有key
    • hvals(name)返回所有value
    • hexisits(name,key)判断这个hash的key在不在
    • hdel(name,*keys)删除指定的键值对
    • hinrby(name,key,amount=1)
posted @ 2019-10-22 23:06  巫小诗  阅读(219)  评论(0编辑  收藏  举报