Django视图层核心组件与请求处理详解
1. 视图层三大核心函数
1.1 HttpResponse
[1] 基础概念
HttpResponse是Django中构建HTTP响应的基础类,负责向客户端返回数据和状态信息。适用于返回纯文本或HTML内容。
[2] 返回文本数据
创建Django应用app01:
python manage.py startapp app01
在app01/views.py中定义视图:
from django.shortcuts import render, HttpResponse
def response_text(request):
return HttpResponse('Hello from Django view')
配置URL路由:
# app01/urls.py
from django.urls import path
from app01.views import response_text
urlpatterns = [
path('text/', response_text, name='text_response')
]
# 项目主urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app01/', include('app01.urls')),
]
[3] 返回JSON数据
直接返回字典:
import json
def json_response_direct(request):
data = {'user': 'john', 'score': 95}
return HttpResponse(data) # 返回字典键名
正确返回JSON格式:
def json_response_proper(request):
data = {'user': 'john', 'score': 95}
json_data = json.dumps(data)
return HttpResponse(json_data, content_type='application/json')
1.2 render函数
[1] 基本用途
render函数结合模板引擎,用于渲染包含动态数据的HTML页面。
[2] 传递上下文数据
函数签名:render(request, template_name, context=None, content_type=None, status=None, using=None)
def render_example(request):
user_info = {'username': 'alice', 'level': 4}
return render(request, 'profile.html', user_info)
模板文件profile.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户资料</title>
</head>
<body>
<p>用户名:{{ username }}</p>
<p>等级:{{ level }}</p>
</body>
</html>
[3] 使用局部变量
def profile_view(request):
name = "张三"
age = 25
skills = ["Python", "Django", "JavaScript"]
return render(request, 'profile.html', locals())
模板中使用:
<h1>{{ name }}</h1>
<p>年龄:{{ age }}</p>
<ul>
{% for skill in skills %}
<li>{{ skill }}</li>
{% endfor %}
</ul>
1.3 redirect函数
用于HTTP重定向,无特殊补充内容。
2. JsonResponse优化JSON响应
2.1 核心优势
相比HttpResponse手动处理JSON,JsonResponse具有以下优点:
- 自动序列化:无需手动调用json.dumps()
- 正确MIME类型:自动设置Content-Type为application/json
- 代码简洁:减少重复代码
2.2 实现方式
[1] 中文编码问题
import json
def chinese_json_manual(request):
data = {'姓名': '李四', '城市': '北京'}
json_str = json.dumps(data, ensure_ascii=False)
return HttpResponse(json_str, content_type='application/json')
[2] JsonResponse标准用法
from django.http import JsonResponse
def chinese_json_response(request):
data = {'姓名': '李四', '城市': '北京'}
return JsonResponse(data, json_dumps_params={'ensure_ascii': False})
3. 文件上传处理
3.1 Form表单基础
文件上传必需条件:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file">
<button type="submit">上传</button>
</form>
3.2 文件接收与保存
import os
from django.shortcuts import render, redirect
def file_upload(request):
if request.method == 'GET':
return render(request, 'upload.html')
# 获取上传文件
uploaded_file = request.FILES.get('upload_file')
if uploaded_file:
# 读取文件内容
file_content = uploaded_file.read()
# 构建保存路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
save_directory = os.path.join(project_root, 'media', 'uploads')
os.makedirs(save_directory, exist_ok=True)
# 保存文件
file_path = os.path.join(save_directory, uploaded_file.name)
with open(file_path, 'wb') as f:
f.write(file_content)
return redirect('file_upload')
4. Request对象扩展属性
| 属性方法 | 查询参数 | 脚本前缀 | 主要用途 |
|---|---|---|---|
request.path |
不包含 | 包含 | 完整路径(含部署前缀) |
request.path_info |
不包含 | 不包含 | 纯路由路径 |
request.get_full_path() |
包含 | 包含 | 完整URL(含参数+前缀) |
request.get_full_path_info() |
包含 | 不包含 | 路由完整路径(含参数) |
5. FBV与CBV模式对比
5.1 基本概念
- FBV (Function-Based Views):基于函数的视图
- CBV (Class-Based Views):基于类的视图
5.2 CBV实现方式
from django.views import View
from django.http import HttpResponse
class UserView(View):
def get(self, request):
return HttpResponse("GET请求处理")
def post(self, request):
return HttpResponse("POST请求处理")
URL配置:
from django.urls import path
from app01.views import UserView
urlpatterns = [
path('user/', UserView.as_view(), name='user_view')
]
5.3 CBV执行流程
- 项目启动时执行
as_view()方法 - 返回闭包函数
view - 请求到达时调用
view函数 view调用dispatch方法dispatch根据HTTP方法调用对应处理函数