0


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

在这里插入图片描述

在这里插入图片描述

目录

视图在接收请求并处理后,必须返回

  1. HttpResponse

对象或⼦对象。

  1. HttpRequest

对象由

  1. Django

创建,

  1. HttpResponse

对象由开发⼈员创建。

  1. classHttpResponse(HttpResponseBase):"""
  2. An HTTP response class with a string as content.
  3. This content that can be read, appended to, or replaced.
  4. """
  5. streaming =Falsedef__init__(self, content=b'',*args,**kwargs):super().__init__(*args,**kwargs)# Content is a bytestring. See the `content` property methods.
  6. self.content = content
  7. 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,}defserialize(self):"""Full HTTP message, including headers, as a bytestring."""return self.serialize_headers()+b'\r\n\r\n'+ self.content
  8. __bytes__ = serialize
  9. @propertydefcontent(self):returnb''.join(self._container)@content.setterdefcontent(self, value):# Consume iterators upon assignment to allow repeated iteration.ifhasattr(value,'__iter__')andnotisinstance(value,(bytes,str)):
  10. content =b''.join(self.make_bytes(chunk)for chunk in value)ifhasattr(value,'close'):try:
  11. value.close()except Exception:passelse:
  12. content = self.make_bytes(value)# Create a list of properly encoded bytestrings to support write().
  13. self._container =[content]def__iter__(self):returniter(self._container)defwrite(self, content):
  14. self._container.append(self.make_bytes(content))deftell(self):returnlen(self.content)defgetvalue(self):return self.content
  15. defwritable(self):returnTruedefwritelines(self, lines):for line in lines:
  16. self.write(line)

1. HttpResponse

可以使⽤

  1. django.http.HttpResponse

来构造响应对象。

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

也可通过

  1. HttpResponse

对象属性来设置响应体、响应体数据类型、状态码:

  • content:表示返回的内容。
  • status_code:返回的HTTP响应状态码。 响应头可以直接将HttpResponse对象当做字典进⾏响应头键值对的设置:
  1. response = HttpResponse('bei ji de san ha !')
  2. response['bei ji de san ha !']='Python'# ⾃定义响应头bei ji de san ha, 值为Python

示例:

  1. from django.shortcuts import render
  2. from django.http import HttpResponse
  3. # Create your views here.defresponse(request):return HttpResponse(content='Hello HttpResponse', content_type=str, status=400)

或者:

  1. from django.shortcuts import render
  2. from django.http import HttpResponse
  3. # Create your views here.defresponse(request):# return HttpResponse(content='Hello HttpResponse', content_type=str, status=400)
  4. response = HttpResponse('bei ji de san ha !')
  5. response.status_code =400
  6. response['bei ji de san ha !']='Python'return respons

2. HttpResponse⼦类

  1. Django

提供了⼀系列

  1. HttpResponse

的⼦类,可以快速设置状态码。

  1. HttpResponseRedirect 301
  2. HttpResponsePermanentRedirect 302
  3. HttpResponseNotModified 304
  4. HttpResponseBadRequest 400
  5. HttpResponseNotFound 404
  6. HttpResponseForbidden 403
  7. HttpResponseNotAllowed 405
  8. HttpResponseGone 410
  9. HttpResponseServerError 500

示例:

  1. HttpResponseRedirect 301

视图函数:

  1. from django.shortcuts import render
  2. from django.http import HttpResponse, HttpResponseRedirect
  3. # Create your views here.defresponse(request):return HttpResponseRedirect('/hrv/')defhttpResponseView(request):return HttpResponse('Hello Django HttpResponse')

路由:

  1. # -*- coding: utf-8 -*-# @File : urls.py# @author: 北极的三哈# @email : Flymeawei@163.com# @Time : 2022/10/31 上午2:35""""""from django.urls import path, re_path
  2. from papp import views
  3. urlpatterns =[
  4. path('response/', views.response),
  5. path('hrv/', views.httpResponseView),]

访问:

  1. 127.0.0.1:8000/response/

在这里插入图片描述

响应:

  1. http://127.0.0.1:8000/hrv/

在这里插入图片描述

3. JsonResponse

  1. classJsonResponse(HttpResponse):"""
  2. An HTTP response class that consumes data to be serialized to JSON.
  3. :param data: Data to be dumped into json. By default only ``dict`` objects
  4. are allowed to be passed due to a security flaw before EcmaScript 5. See
  5. the ``safe`` parameter for more information.
  6. :param encoder: Should be a json encoder class. Defaults to
  7. ``django.core.serializers.json.DjangoJSONEncoder``.
  8. :param safe: Controls if only ``dict`` objects may be serialized. Defaults
  9. to ``True``.
  10. :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
  11. """def__init__(self, data, encoder=DjangoJSONEncoder, safe=True,
  12. json_dumps_params=None,**kwargs):if safe andnotisinstance(data,dict):raise TypeError('In order to allow non-dict objects to be serialized set the ''safe parameter to False.')if json_dumps_params isNone:
  13. json_dumps_params ={}
  14. kwargs.setdefault('content_type','application/json')
  15. data = json.dumps(data, cls=encoder,**json_dumps_params)super().__init__(content=data,**kwargs)

若要返回

  1. json

数据,可以使⽤

  1. JsonResponse

来构造响应对象,作⽤:

  • 帮助我们将数据转换为json字符串
  • 设置响应头Content-Typeapplication/json
  1. from django.shortcuts import render
  2. from django.http import HttpResponse, JsonResponse
  3. # Create your views here.defresponse(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 responsereturn JsonResponse({'uname':'san ha','age':22})

访问:

  1. http://127.0.0.1:8000/response/

JSON在这里插入图片描述

原始数据
在这里插入图片描述


在这里插入图片描述

4. redirect重定向

  1. defredirect(to,*args, permanent=False,**kwargs):"""
  2. Return an HttpResponseRedirect to the appropriate URL for the arguments
  3. passed.
  4. The arguments could be:
  5. * A model: the model's `get_absolute_url()` function will be called.
  6. * A view name, possibly with arguments: `urls.reverse()` will be used
  7. to reverse-resolve the name.
  8. * A URL, which will be used as-is for the redirect location.
  9. Issues a temporary redirect by default; pass permanent=True to issue a
  10. permanent redirect.
  11. """
  12. redirect_class = HttpResponsePermanentRedirect if permanent else HttpResponseRedirect
  13. return redirect_class(resolve_url(to,*args,**kwargs))

视图函数:

  1. from django.shortcuts import render
  2. from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
  3. from django.shortcuts import redirect
  4. # Create your views here.defresponse(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 response# return JsonResponse({'uname': 'san ha', 'age': 22})# return HttpResponseRedirect('/hrv/')return redirect('/hrv/')defhttpResponseView(request):return HttpResponse('Hello Django HttpResponse')

路由:

  1. # -*- coding: utf-8 -*-# @File : urls.py# @author: 北极的三哈# @email : Flymeawei@163.com# @Time : 2022/10/31 上午2:35""""""from django.urls import path, re_path
  2. from papp import views
  3. urlpatterns =[
  4. path('response/', views.response),
  5. path('hrv/', views.httpResponseView),]

访问:

  1. 127.0.0.1:8000/response/

在这里插入图片描述

响应:

  1. http://127.0.0.1:8000/hrv/

在这里插入图片描述

标签: django python 后端

本文转载自: https://blog.csdn.net/m0_68744965/article/details/127615877
版权归原作者 北极的三哈 所有, 如有侵权,请联系我们删除。

“【Django框架】——23 Django视图 05 HttpResponse对象”的评论:

还没有评论