前后端分离怎么使用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)})