django的视图函数使用redis一个例子

本文介绍了一种前后端分离架构下利用Redis进行数据缓存的方法。通过将请求路径作为Redis的键值,实现了一个装饰器来扩展请求功能,从而达到自动缓存和读取数据的目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前后端分离怎么使用redis存数据和取数据?下面是一个示例..... 

 

把数据以json格式存放在redis中, 写一个装饰器,扩展请求的功能, 使得能够让逻辑函数从redis取数据和存数据

 

redis中, 请求路径request.path作为redis的key,

#装饰器
def cache_view(func):
    def _wrapper(self,request, *args,**kwargs):
        con = get_redis_connection()
        data = con.get(request.path)

        if data:
            print("缓存中有数据,返回缓存中的数据")
        

            data = json.loads(data)#把缓存中的数据以python普通数据结构显示(即是字典)
            return JsonResponse({'code': '1', 'data': data})


        response = func(self,request,*args,**kwargs)#redis无缓存,从mysql取数据
        

        print("要缓存数据....")
        

        data = response.content#获取响应对象JsonResponse的数据
        
       
        data = json.loads(data)#json转成python的字典
        if data.get("code") == "1":##这是我个人的,状态码1是查到数据,查到就缓存
            con.set(request.path,json.dumps(data,ensure_ascii=False))
        return JsonResponse({'code': '1', 'data': data})

    return _wrapper

class PostView(View):
    @cache_view
    def get(self, request):#使用装饰器cache_view
        try:
            # posts = Post.objects.all().order_by("-created").values("id", "title", "created")
            # posts = list(posts)

            cursor = connection.cursor()
            sql = "select post.id, title, created, category.categoryName from post, category where category.id = post.category_id order by post.created desc"
            cursor.execute(sql)
            res = cursor.fetchall()
            cursor.close()
            dict_res = []
            for i in res:
                dict = {
                    "id": i[0],
                    "title": i[1],
                    "created": i[2],
                    "categoryName": i[3]
                }
                dict_res.append(dict)
            # print(JsonResponse({'code': '1', 'data': dict_res}).content)
            return JsonResponse({'code': '1', 'data': dict_res})

        except Exception as e:
            return JsonResponse({'code': '0', 'msg': '请求后端数据错误' + str(e)})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值