django如何请求返回不同的类型图片json,xml,html

这篇文章给大家分享的是有关django如何请求返回不同的类型图片json,xml,html的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

django 返回数据的主要是用django.http.HttpResponse 中的HttpResponse 完成的

具体的我直接贴代码吧

from django.http import HttpResponse
### 引用
def index(request):
 if request.GET["type"] == "img":
  return HttpResponse(open("test.png","rb"),content_type="image/png")
  ## 这里 返回图片
 elif request.GET["type"] == "html":
  return HttpResponse(open("1.html","rb"),content_type="text/html")
  ## 返回 html文本
 elif request.GET["type"] == "xml":
  return HttpResponse(open("1.html","rb"),content_type="text/xml")
  ##返回 xml文本
 elif request.GET["type"] == "json":
  return HttpResponse({"code":"ok"},content_type="application/json")
  ##返回 json文本
 
from django.http import JsonResponse
def index(request):
 
 return JsonResponse({"code":"ok"})
 ## 这里的JsonResponse 更加简便的返回了json

感谢各位的阅读!关于“django如何请求返回不同的类型图片json,xml,html”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!