Django的JsonResponse二次封装
Posted Jason_WangYing
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django的JsonResponse二次封装相关的知识,希望对你有一定的参考价值。
# 在视图中写视图类
import json
from django.http import HttpResponseRedirect,JsonResponse
class HttpCode(object):
ok = 200
paramserror = 400
unauth = 401
methoderror = 405
servererror = 500
def result(data=None, code=HttpCode.ok, message="moren", kwargs=None):
json_dict = {"code":code, "message":message,"data":data}
if kwargs and isinstance(kwargs, dict) and kwargs.keys():
json_dict.update(kwargs)
return JsonResponse(json_dict)
class BaseJasonResponse(JsonResponse):
def __init__(self,data= None,code=HttpCode.ok,message = '默认消息'):
res = {"code":code, "message":message,"data":data}
super().__init__(res)
def apiGet(request):
if request.method == "GET":
id = request.GET.get("id",'')
pid = request.GET.get("pid",'')
if id and pid:
return BaseJasonResponse('{"data2": "这是一个错误的消息2222", "msg2": "query articles sucess.222"}')
# return HttpResponseRedirect("http://www.baidu.com")
return result({'data2':{"code2": 122, "data2": "这是一个错误的消息2222", "msg2": "query articles sucess.222"}})
# return HttpResponseRedirect("hts://www.cnblogs.com/jiangxianseng/p/12883142.html")
else:
return HttpResponseRedirect("https://zhuanlan.zhihu.com/p/30058745")
线上代码,我写了两个,一个是类方法,直接把JsonResponse类扩展,一个是封装成方法,直接传递值。
以上是关于Django的JsonResponse二次封装的主要内容,如果未能解决你的问题,请参考以下文章
Django HttpResponse与JsonResponse对象
django之HTTPResponse和JsonResponse详解