網上雖然也有一些示例,但是因為Django和Python的版本升級,所以網上的例子就不能直接應用了,需要做一些修改。
具體的實現方法如下:
from django.http import HttpResponse from json import loads, dumps def json_response_demo(request): dic = {} try:
if request.method == 'POST': print('post info: ', request.body)
jstr = loads((request.body).decode())
print(jstr)
return HttpResponse(jstr, content_type="application/json")
except:
import sys
print(sys.exc_info()[0], sys.exc_info()[1])
dic['message'] = "A beautiful json string response."
dic['create_at'] = str(ctime())
jstr = dumps(dic)
return HttpResponse(jstr, content_type='application/json')