微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【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 : [email protected]
# @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 @R_71_4045@ion.
    :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 @R_502_5285@ 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 : [email protected]
# @Time  : 2022/10/31 上午2:35
""""""
from django.urls import path,
]

访问:127.0.0.1:8000/response/

在这里插入图片描述

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

在这里插入图片描述

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

相关推荐