zoukankan      html  css  js  c++  java
  • HttpResponse属性

    HttpResponse含义:

    Django服务器接收到客户端发送过来的请求后,会将提交上来的这些数据封装成一个HttpRequest对象传给视图函数。那么视图函数在处理完相关的逻辑后,也需要返回一个响应给浏览器。而这个响应,我们必须返回HttpResponseBase或者他的子类的对象。而HttpResponse则是HttpResponseBase用得最多的子类。

    常用属性及其含义:

    1. content:返回的内容。
    2. status_code:返回的HTTP响应状态码。
      def index(request):
          response.content='wanrou'  #相当于response = HttpResponse('wanrou')
          response.status_code=400   #设置错的HTTP响应状态码  在network中查看
          return response
    3. content_type:返回数据MIME媒体类型(简称MIME类型)默认是text/html。常见得content-type类型如下:

      text/html(默认的,html文件)

      text/plain(纯文本)

      text/css(css文件)

      text/javascript(js文件)

      multipart/form-data(文件提交)

      application/json(json传输)

      application/xml(xml文件)

    4. 设置请求头:response['X-Access-Token'] = 'xxx'

    常用方法:

    1. set_cookie:用来设置cookie信息.
    2. delete_cookie:用来删除cookie信息
    3. write:HttpResponse是一个类似于文件的对象,可以用来写入数据到数据中
      def index(request):
          response = HttpResponse('hello')
          response.write('everyone')
          return response

    JsonResponse

    把对象dump成json字符转,然后返回将json字符串封装成Response对象返回给浏览器。

    from django.http import JsonResponse
    def index(request):
    a=JsonResponse({"username":"wanrou","age":18})
    return a

    他的对象只能是字典,如果要给给字典数据进行jump,需要增加safe=False参数

    from django.http import JsonResponse
    def index(request):
        persons = ['张三','李四','王五']
        return HttpResponse(persons,safe=False)   #如果不增加safe=False网页会报错
  • 相关阅读:
    指针+[][]T 类型
    linux适用小工具-tmux
    wrk+lua进行压力测试
    brew更换为国内源
    k8s证书更新
    ssh隧道
    kubeadm安装集群系列(kubeadm 1.15.1)
    harbor清理存储
    第十周课程总结
    第九周课程总结&第七次实验报告
  • 原文地址:https://www.cnblogs.com/nihao2/p/12266227.html
Copyright © 2011-2022 走看看