Django HttpResponse 响应对象

django-ide


目录

    • 一、概述
    • 二、测试
    • 三、属性和方法
    • 四、解读 request 参数


一、概述

所谓 HttpRequest 响应就是服务器返回给客户端的数据,HttpRequest 由程序员自己创建,一般他们通过两种方式来创建。

  1. 不使用模板,直接调用 HttpResponse(),返回 HttpResponse 对象;

  2. 通过 render() 函数调用模板(templates)进行渲染

    # render() 函数语法
    render(request, template_name, [context])
    
    # 函数参数说明
    # request:上面刚提到,即客户端的请求信息
    # template_name:模板名,如index.html
    # context:这是一个可选的字典类型参数,该参数用于传入模板中,从而更好地渲染模板
    

还有就是 HttpResponse 的一些子类也可实现响应。

  1. HttpResponseRedirect

    # 可实现服务器内部跳转(但还是推荐使用反向解析)
    return HttpResponseRedirect('/grade/2030')
    

    扩展:也可使用 redirect() 进行重定向,也就是说它与 HttpResponseRedirect 是等价的。

  2. JsonResponse

    # 返回Json数据的请求,通常用在异步请求上
    JsonResponse(dict)    # 将字典转为Json格式
    

二、测试

1、视图函数

def my_response(request):
    # 1.返回字符串:企业项目中很少使用
    # return HttpResponse('ok')

    # 2.返回模板(用于前后端不分离的情况,即前后端代码放在一个工程下面,后端返回数据后,直接将数据渲染模板)
    # return render(request, 'index.html')

    # 3.重定向(一般用于页面跳转)
    # return redirect('/request/')
    # return HttpResponseRedirect('/request/')

    # 4.返回Json数据*(用于前后端不分离的情况,即后端只需返回数据给前端,前端拿到数据后自己去渲染)
    return JsonResponse({'data': 'hello'})

2、路由

from django.urls import path
from user.views import index, my_request, my_response

urlpatterns = [
    path('user/', index, name='index'),
    path('request/', my_request, name='my_request'),
    path('response/', my_response, name='my_response'),
]

3、请求

Django HttpResponse 响应对象_第1张图片

三、属性和方法

一般很少用,常见属性和方法有一下几种:

1、属性

  • content:返回的内容;
  • charset:返回的编码格式;
  • status_code:返回的响应状态码。

2、方法

  • write():直接写出文本;
  • flush():冲刷缓冲区;
  • set_cookie(key, value=‘xxx’, max_age=None):设置cookie;
  • delete_cookie(key):删除cookie。

四、解读 request 参数

>>> 疑问?来自 GPT 的回答

Django HttpResponse 响应对象_第2张图片

Django HttpResponse 响应对象_第3张图片

# 1.视图函数(views.py)
from django.shortcuts import render

def index(request):
    # 渲染模板render,渲染HTML
    return render(request, 'index.html')
# 2.模板文件(templates/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>首页</h2>
    <hr>
    <h4>Hello Django!</h4>
</body>
</html>
# 3.路由(urls.py)
from django.contrib import admin
from django.urls import path
from user.views import *

urlpatterns = [
    path('index/', index),
    path('admin/', admin.site.urls),
]

因此,想这个案例流程就是:当客户端向我的 Django 项目 Web 服务发起 HTTP 请求时,Django 将获取客户端的请求信息,如请求方法GET、POST 及 URL 信息等(由 request 获取)。

  • 客户端请求:http://xxx/index/
  • Django 获取客户端请求的 URL 为 index
  • 于是路由到 Django 视图函数 index,即上面的 path('index/', index)
  • 而该函数是有模板渲染的,且模板文件为 index.html,即上面视图函数中 return render(request, 'index.html')
  • 因此,Django 通过 render() 函数渲染 index.html 后,将渲染的结果响应给客户端。

—END

你可能感兴趣的:(Django,django)