自学Python之路-django视图--响应对象HttpResponse、JsonResponse、render、重定向redirect

 响应对象主要有三种形式:

  • HttpResponse()
  • render()    本质也是返回HttpResponse()
  • redirect()   重定向

响应对象 HttpResponse()

Django服务器接收到客户端发送过来的请求后,会将提交上来的这些数据封装成一个 HttpRequest 对象传给视图函数。那么视图函数在处理完相关的逻辑之后,也需要返回一个响应对象给浏览器。 HttpResponse对象由程序员创建并返回。

属性 说明
content 字节字符串,返回的内容。
charset 字符编码
status_code http状态码
content_type 指定输出的MIME类型,默认为text/html。浏览器会根据这个属性,来显示数据。如果是text/html,那么就会解析这个字符串,如果 text/plain,那么就会显示一个纯文本。

常用的状态码status_code如下:

状态码含义
200 响应成功
301 永久重定向,Location属性的值为当前的URL
302 临时重定向,Location属性的值为新的URL
404 URL不存在
403 未授权访问
500 内部服务器报错
502 网关错误
503 服务不可用
def  handle_respone(reqest):
res = HttpResponse("响应对象")
res.content = b'goodbye'
res.charset = "utf-8"
res.content_type = "text/html"
return res
urlpatterns = [
   # 响应对象
    path('response/',views.handle_respone,name='respone'),
]

 

1  响应对象JsonResponse

  • JsonResponse是HttpResponse的子类,用于向客户端返回json的数据。一般用于ajax请求
  • 用来对象 dump 成 json字符串,然后返回将 json 字符串封装成Response 对象返回给浏览器。并且它的Content-Type缺省值是 application/json
from django.http import JsonResponse  # 导入包
     class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)

参数:

  • JsonResponse对象的默认Content-Type头部设置为application/json
  • data:应该为一个dict实例。如果safe参数设置为False,它可以传递任何JSON对象进行序列化(否则,只允许dict实例)
  • encoder:缺省是 django.core.serializers.json.DjangoJSONEncoder,用于序列化data
  • 布尔参数safe:默认为 True。如果设置为False,可以传递任何对象进行序列化(否则,只允许dict实例)。如果safe为True,而第一个参数传递的不是dict对象,将抛出一个TypeError
  • json_dumps_params是一个字典,它是在生成响应时,传给json.dumps()的参数
from django.http import JsonResponse
   def  handle_respone(request):
       return JsonResponse({'name':'carlos'})    #对字典,可以返回json字符串

def  handle_respone(request):
    return JsonResponse([1,2,3,4,5,6,7,8,9,8,8,8,8,8,],safe=False)  # 如果参数不是字典,将参数设置safe=False

 2   响应对象  render()函数

  • 一般的render函数返回,render只是HttpReponse的包装,还是会返回HttpReponse的对象。
  • render主要是将从服务器提取的数据,填充到模板中,然后将渲染后的html静态文件返回给浏览器。
  • 这里一定要注意:render渲染的是模板
def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Return a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

参数:

  • request: 是一个固定参数
  • template_name: templates中定义的文件,注意路径名。比如:“templates/polls/index.html”, 则参数这样写:“polls/index.html”
  • context: 要传入文件中用于渲染呈现的数据,一组字典的值添加到模板中。默认情况下,这是一个空的字典。
  • content_type: 生成的文档要使用的MIME 类型。默认为DEFAULT_CONTENT_TYPE 设置的值。
  • status: http的响应代码,默认是200。
  • using: 用于加载模板使用的模板引擎的名称。
def studentlist(req):
     for key in req.GET.lists():
        print(key)
     allstudent = Student.objects.all()
     return render(req,'studentlist.html',context={'data':allstudent})

常用的方法:

  • write(content) 设置内容 == obj.content
  • set_cookie() 设置cookie
  • delete_cookie() 删除cookie

以下举例:

def  handle_respone(request):
    # render 返回响应对象
    res = render(request,'example1.html')
    return res

3   响应对象  重定向redirect

  • 当浏览器向server发送一个请求,要求获取一个资源时,在server接收到这个请求后发现请求的这个资源实际存放在另一个位置,于是server在返回的response中写入那个请求资源的正确的URL,并设置reponse的状态码为301(表示这是一个要求浏览器重定向的response),当client接受到这个response后就会根据新的URL重新发起请求。
  • 重定向有一个典型的特症,即:当一个请求被重定向以后,最终浏览器上显示的URL往往不再是开始时请求的那个URL了。这就是重定向的由来
  • HttpResponseRedirect是HttpResponse的子类,可以完成页面的重定向,当执行完特定动作或出现错误时,我们会希望执行的页面,如果判定用户没有登录则转到登录页面。
  • 重定向可以直接写成redirect,redirect是HttpResponseRedirect的简写。
  • HttpResponseRedirect只支持硬编码url,不能直接使命名url,在使URL命名时,我们需要先通过URL反向解析方法reverse先对命名URL进行解析,然后再使HttpReponseRedirect定向。
使用时需要导入:
     from django.http import HttpResponseRedirect

3.1 不带参数重定向

#views代码:
from django.http import HttpResponseRedirect
from django.shortcuts import render,HttpResponse,redirect

def index(request):
    return HttpResponse("首页")

def handle_redirect(request):
    #HttpResponseRedirect重定向到指定路由地址,参数就是路由
#redirect是
HttpResponseRedirect缩写
    return HttpResponseRedirect("/user/") 

#APP\urls 子路由代码:
urlpatterns
= [
path(
'', views.index, name='index'),
# 重定向
path(
'red/',views.handle_redirect,name='red')
]

浏览器中输入http://127.0.0.1:8000/user/red/ ,会直接重定向至http://127.0.0.1:8000/user/

3.2  带参数重定向

#APP\urls.py 子路由代码
path('repath/<int:num>/', views.repath),
re_path(r'^parameter/(?P<num1>\d+)/(?P<num2>\d+)/$',views.parameter),

#views.py  代码
def repath(req,num):
    return redirect("parameter/3/5")
def index(request):
    return HttpResponse("首页")
def parameter(req,num1, num2):
    return HttpResponse("num1={},num2={}".format(num1,num2))

可以直接重定向到其他网页:

 

#views.py 代码
def handle_redirect(request):
    return redirect("https://www.baidu.com/")

#APP\urls.py 子路由代码
urlpatterns = [
    path('', views.index, name='index'),
    path('red/',views.handle_redirect,name='red'),
]

 

浏览器中输入http://127.0.0.1:8000/user/red/ ,会直接重定向至百度www.baidu.com

3.3  反向解析

由应用命名空间,name来确定路由。。。根据namespace 和 name 查找真实路径:

  • namespace 在根url 包含子url时指定
  • name 在具体的函数后指定子url指定
# urls.py中
app_name = 'App' # namespace 命名空间
urlpatterns = [
   path('', views.index),
   path('para/<int:num1>/<int:num2>/'),
]

#python代码中写法
def repath(req):
   # res = reverse("App:index")
   # print(res,type(res))
   # return redirect(res)
   # path中参数或re_path中的位置参数,args可以是列表或元组
   # return redirect(reverse("App:para",args=(1,2)))
   # re_path中命名组,带关键字参数
   return redirect(reverse("App:para",kwargs={'num1':1,'num2':3}))

render和redirect两者区别:

  • 第一,假如render返回一个登陆成功后的页面,刷新该页面将回复到跳转前页面。而redirect则不会
  • 第二,如果页面需要模板语言渲染,需要的将数据库的数据加载到html,那么render方法则不会显示这一部分,render返回一个登陆成功页面,不会经过url路由分发系统,也就是说,不会执行跳转后url的视图函数。这样,返回的页面渲染不成功;而redirect是跳转到指定页面,当登陆成功后,会在url路由系统进行匹配,如果有存在的映射函数,就会执行对应的映射函数。

.......

posted on 2023-03-10 07:21  CARLOS_KONG  阅读(359)  评论(0编辑  收藏  举报

导航