Django HttpResponse 响应对象


目录


一、概述

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

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

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

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

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

  1. HttpResponseRedirect

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

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

  2. JsonResponse

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

二、测试

1、视图函数

py 复制代码
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、路由

py 复制代码
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、请求

三、属性和方法

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

1、属性

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

2、方法

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

四、解读 request 参数

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

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

def index(request):
    # 渲染模板render,渲染HTML
    return render(request, 'index.html')
py 复制代码
# 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>
py 复制代码
# 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

相关推荐
会编程的吕洞宾1 天前
DeepAgents In Action学习(Third)
python·学习·django
FYKJ_20101 天前
django学习成绩预警系统10905
java·javascript·spring boot·python·spark·django·php
言乐62 天前
Python实现自动拉人脚本示例
开发语言·windows·python·django·pygame
践行见远3 天前
django之配置文件加载
django
【赫兹威客】浩哥3 天前
【无标题】
python·spring·django·pyqt
winfredzhang3 天前
从零构建家庭照片管理系统:Django 模块化单体实战,以及我踩到的 4 个真实坑
python·postgresql·django·sqlite·bootsrap
weixin_BYSJ19873 天前
springboot智慧公共交通系统---附源码51123
java·javascript·spring boot·python·django·flask·php
衿心.3 天前
Django TemplateDoesNotExist
数据库·django·sqlite
weixin_BYSJ19874 天前
springboot游戏账号租赁系统---附源码50345
java·spring boot·python·游戏·django·flask·php
SelectDB技术团队5 天前
腾讯音乐内容库 ES 替代:从 Elasticsearch 到 Apache Doris 统一搜索分析引擎实践
elasticsearch·django·apache doris