目录
视图在接收请求并处理后,必须返回
HttpResponse
对象或⼦对象。
HttpRequest
对象由
Django
创建,
HttpResponse
对象由开发⼈员创建。
classHttpResponse(HttpResponseBase):"""
An HTTP response class with a string as content.
This content that can be read, appended to, or replaced.
"""
streaming =Falsedef__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,}defserialize(self):"""Full HTTP message, including headers, as a bytestring."""return self.serialize_headers()+b'\r\n\r\n'+ self.content
__bytes__ = serialize
@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)):
content =b''.join(self.make_bytes(chunk)for chunk in value)ifhasattr(value,'close'):try:
value.close()except Exception:passelse:
content = self.make_bytes(value)# Create a list of properly encoded bytestrings to support write().
self._container =[content]def__iter__(self):returniter(self._container)defwrite(self, content):
self._container.append(self.make_bytes(content))deftell(self):returnlen(self.content)defgetvalue(self):return self.content
defwritable(self):returnTruedefwritelines(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.defresponse(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.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 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.defresponse(request):return HttpResponseRedirect('/hrv/')defhttpResponseView(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
classJsonResponse(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 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:
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-Type
为application/json
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
# 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})
访问:
http://127.0.0.1:8000/response/
JSON
原始数据
头
4. redirect重定向
defredirect(to,*args, 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,*args,**kwargs))
视图函数:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.shortcuts import redirect
# 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')
路由:
# -*- 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/
版权归原作者 北极的三哈 所有, 如有侵权,请联系我们删除。