api.py
from dss.Serializer import serializer
from django.http import HttpResponse
def response_as_json(data, foreign_penetrate=False):
jsonString = serializer(data=data, output_type="json", foreign=foreign_penetrate)
response = HttpResponse(
jsonString,
content_type="application/json",
)
response["Access-Control-Allow-Origin"] = "*"
return response
def json_response(data='', msg='Data Interface Callback Successful.', code=200, foreign_penetrate=False, **kwargs):
res_data = {
'code': code,
'msg': msg,
'data': data,
}
res_data.update(kwargs)
return response_as_json(res_data, foreign_penetrate=foreign_penetrate)
def json_error(data='', msg='Unknown error!', code=500, **kwargs):
res_data = {
'code': code,
'msg': msg,
'data': data,
}
res_data.update(kwargs)
return response_as_json(res_data)
views.py 使用
from utils import api
JsonResponse = api.json_response
JsonError = api.json_error
def get_func(request):
if request.method == "GET":
res = []
img_path = 'media/img/asdf.gif'
res = [img_path, img_path]
return JsonResponse(res)
标签:code,res,接口,Django,json,设置,msg,data,response
From: https://www.cnblogs.com/jessecheng/p/16935602.html