django中间件处理返回数据
统一接口返回数据格式的时候,每个视图都需要返回JsonResponse
对象,比较麻烦,因此增加中间件处理视图返回的结果。
from django.http.response import JsonResponse, HttpResponseBase
code_msg_map = {
0: 'ok',
1: 'The args missing.',
1000: 'The file does not exist.',
}
class ResponseMiddleware:
"""包装视图返回的数据,创建 JsonResponse 对象"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
# 包装返回的数据
if not isinstance(response, HttpResponseBase):
if isinstance(response, int):
# 只返回错误码,没有数据,默认为 {}
response = JsonResponse({'code': response, 'msg': code_msg_map.get(response, ''), 'data': {}})
elif isinstance(response, tuple):
# 包括错误码和数据
code, data = response
response = JsonResponse({'code': code, 'msg': code_msg_map.get(code, ''), 'data': data})
else:
# 只有数据,错误码默认为 0
response = JsonResponse({'code': 0, 'msg': code_msg_map.get(0, ''), 'data': response})
return response
标签:返回,code,get,JsonResponse,中间件,django,msg,response
From: https://www.cnblogs.com/shouwangrenjian/p/17842577.html