【Django框架】——23 Django视图 05 HttpResponse对象

在这里插入图片描述

在这里插入图片描述


视图在接收请求并处理后,必须返回 HttpResponse对象或⼦对象。

HttpRequest对象由Django创建,HttpResponse对象由开发⼈员创建。

class HttpResponse(HttpResponseBase):
    """
    An HTTP response class with a string as content.

    This content that can be read,appended to,or replaced.
    """

    streaming = False

    def __init__(self, content=b'', *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Content is a bytestring. See the `content` property methods.
        self.content = content

    def __repr__(self):
        return '<%(cls)s status_code=%(status_code)d%(content_type)s>' % {
            'cls': self.__class__.__name__,
            'status_code': self.status_code,
            'content_type': self._content_type_for_repr,
        }

    def serialize(self):
        """Full HTTP message,including headers,as a bytestring."""
        return self.serialize_headers() + b'\r\n\r\n' + self.content

    __bytes__ = serialize

    @property
    def content(self):
        return b''.join(self._container)

    @content.setter
    def content(self, value):
        # Consume iterators upon assignment to allow repeated iteration.
        if hasattr(value, '__iter__') and not isinstance(value, (bytes, str)):
            content = b''.join(self.make_bytes(chunk) for chunk in value)
            if hasattr(value, 'close'):
                try:
                    value.close()
                except Exception:
                    pass
        else:
            content = self.make_bytes(value)
        # Create a list of properly encoded bytestrings to support write().
        self._container = [content]

    def __iter__(self):
        return iter(self._container)

    def write(self, content):
        self._container.append(self.make_bytes(content))

    def tell(self):
        return len(self.content)

    def getvalue(self):
        return self.content

    def writable(self):
        return True

    def writelines(self, lines):
        for line in lines:
            self.write(line)

1. HttpResponse

可以使⽤django.http.HttpResponse来构造响应对象。

HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

也可通过HttpResponse对象属性来设置响应体、响应体数据类型、状态码:

  • content:表示返回的内容。

  • status_code:返回的HTTP响应状态码。 响应头可以直接将HttpResponse对象当做字典进⾏响应头键值对的设置:

response = HttpResponse('bei ji de san ha !')
response['bei ji de san ha !'] = 'Python'

# ⾃定义响应头bei ji de san ha,值为Python

示例:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.


def response(request):
    return HttpResponse(content='Hello HttpResponse', content_type=str, status=400)

或者:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.


def response(request):
    # return HttpResponse(content='Hello HttpResponse',content_type=str,status=400)
    response = HttpResponse('bei ji de san ha !')
    response.status_code = 400
    response['bei ji de san ha !'] = 'Python'
    return respons

2. HttpResponse⼦类

Django提供了⼀系列HttpResponse的⼦类,可以快速设置状态码。

HttpResponseRedirect 301
HttpResponsePermanentRedirect 302
HttpResponseNotModified 304
HttpResponseBadRequest 400
HttpResponseNotFound 404
HttpResponseForbidden 403
HttpResponseNotAllowed 405
HttpResponseGone 410
HttpResponseServerError 500

示例:HttpResponseRedirect 301

视图函数:

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect

# Create your views here.


def response(request):
    return HttpResponseRedirect('/hrv/')


def httpResponseView(request):
    return HttpResponse('Hello Django HttpResponse')

路由:

# -*- coding: utf-8 -*-
# @File  : urls.py
# @author: 北极的三哈
# @email : Flymeawei@163.com
# @Time  : 2022/10/31 上午2:35
""""""
from django.urls import path, re_path
from papp import views


urlpatterns = [
    path('response/', views.response),
    path('hrv/', views.httpResponseView),
]

访问:127.0.0.1:8000/response/

在这里插入图片描述

响应:http://127.0.0.1:8000/hrv/

在这里插入图片描述

3. JsonResponse

class JsonResponse(HttpResponse):
    """
    An HTTP response class that consumes data to be serialized to JSON.

    :param data: Data to be dumped into json. By default only ``dict`` objects
      are allowed to be passed due to a security flaw before EcmaScript 5. See
      the ``safe`` parameter for more information.
    :param encoder: Should be a json encoder class. Defaults to
      ``django.core.serializers.json.DjangoJSONEncoder``.
    :param safe: Controls if only ``dict`` objects may be serialized. Defaults
      to ``True``.
    :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
    """

    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super().__init__(content=data, **kwargs)

若要返回json数据,可以使⽤JsonResponse来构造响应对象,作⽤:

  • 帮助我们将数据转换为json字符串

  • 设置响应头Content-Typeapplication/json

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse

# Create your views here.


def response(request):
    # return HttpResponse(content='Hello HttpResponse',status=400)

    # response = HttpResponse('bei ji de san ha !')
    # response.status_code = 400
    # response['bei ji de san ha !'] = 'Python'
    # return response

    return JsonResponse({'uname': 'san ha', 'age': 22})

访问:http://127.0.0.1:8000/response/

JSON

在这里插入图片描述

原始数据

在这里插入图片描述


在这里插入图片描述

4. redirect重定向

def redirect(to, permanent=False, **kwargs):
    """
    Return an HttpResponseRedirect to the appropriate URL for the arguments
    passed.

    The arguments could be:

        * A model: the model's `get_absolute_url()` function will be called.

        * A view name,possibly with arguments: `urls.reverse()` will be used
          to reverse-resolve the name.

        * A URL,which will be used as-is for the redirect location.

    Issues a temporary redirect by default; pass permanent=True to issue a
    permanent redirect.
    """
    redirect_class = HttpResponsePermanentRedirect if permanent else HttpResponseRedirect
    return redirect_class(resolve_url(to, **kwargs))

视图函数:

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.shortcuts import redirect

# Create your views here.


def response(request):
    # return HttpResponse(content='Hello HttpResponse',status=400)

    # response = HttpResponse('bei ji de san ha !')
    # response.status_code = 400
    # response['bei ji de san ha !'] = 'Python'
    # return response

    # return JsonResponse({'uname': 'san ha','age': 22})

    # return HttpResponseRedirect('/hrv/')
    
    return redirect('/hrv/')


def httpResponseView(request):
    return HttpResponse('Hello Django HttpResponse')

路由:

# -*- coding: utf-8 -*-
# @File  : urls.py
# @author: 北极的三哈
# @email : Flymeawei@163.com
# @Time  : 2022/10/31 上午2:35
""""""
from django.urls import path,
]

访问:127.0.0.1:8000/response/

在这里插入图片描述

响应:http://127.0.0.1:8000/hrv/

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


注:所有源代码均实测运行过。所有源代码均已上传CSDN,请有需要的朋友自行下载。
继承APIView和ViewSetMixin;作用也与APIView基本类似,提供了身份认证、权限校验、流量管理等。ViewSet在开发接口中不经常用。
一、Django介绍Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。Django 是一个开放源代码的 Web 应用框架,由 Python 写成。Django 遵守 BSD 版权,初次发布于 2005 年 7 月, 并于 2008 年 9 月发布了第一个正式版本 1.0 。Django学习线路Django 采用了 MVT 的软件设计模式,即模型(Model),视图(View)和模板(Template)。这个MVT模式并
本文从nginx快速掌握到使用,gunicorn快速掌握到使用,实现小白快速搭建django项目,并对可能出现的报错进行了分析
uniapp微信小程序订阅消息发送服务通知
Django终端打印SQL语句 1 Setting配置: 2 默认python 使用的MysqlDB连接,Python3 支持支持pymysql 所有需要在app里面的__init__加上下面配置:
url: re_path(&#39;authors/$&#39;, views.AuthorView.as_view()), re_path(&#39;book/(?P\d+)/$&#39;, vie
前提 关于html寻找路线: template 如果在各个APP中存在, Django 会优先找全局template 文件下的html文件,如果全局下的template文件没有相关的html Djan
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
from bs4 import BeautifulSoup#kindeditordef kindeditor(request): s = &#39;&#39;&#39; &lt;li&gt;&lt;s
view.py 配置 html 配置
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
浏览器有一个很重要的概念——同源策略(Same-Origin Policy)。所谓同源是指,域名,协议,端口相同。不同源的客户端脚本(javascript、ActionScript)在没明确授权的情况
自动发送 &gt; 依赖jQuery文件 实例--&gt;GET请求: 手动发送 &gt; 依赖浏览器XML对象(也叫原生ajax) Ajax主要就是使用 【XmlHttpRequest】对象来完成请
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render