django HttpResponse 加返回码

在Django框架中,HttpResponse对象是用来构造HTTP响应并将其发送回客户端的。当你创建一个HttpResponse对象时,你可以指定一个返回码(或状态码),这是HTTP响应的一部分,用来表示请求的处理结果。状态码是三位数字,例如200表示成功,404表示未找到,500表示服务器内部错误等。

创建HttpResponse对象并设置状态码

你可以在创建HttpResponse对象时通过传递一个可选的第二个参数来设置状态码。例如:

from django.http import HttpResponse

def my_view(request):

创建一个HTTP响应,内容为"Hello, world.",状态码为200(默认)

response = HttpResponse("Hello, world.")

return response

def my_view_with_status(request):

创建一个HTTP响应,内容为"Hello, world.",状态码为404

response = HttpResponse("Hello, world.", status=404)

return response

直接使用状态码

你也可以使用HttpResponse的status_code属性来设置状态码,这在响应已经创建之后或者在需要动态改变状态码的情况下很有用。例如:

from django.http import HttpResponse

def my_view(request):

response = HttpResponse("Hello, world.")

设置状态码为404

response.status_code = 404

return response

使用快捷方法返回状态码和内容

Django还提供了一些快捷方法来直接返回状态码和内容,例如HttpResponseNotFound, HttpResponseBadRequest等,这些方法已经为你设置了相应的状态码:

from django.http import HttpResponseNotFound, HttpResponseBadRequest

def my_not_found_view(request):

return HttpResponseNotFound("Page not found.")

def my_bad_request_view(request):

return HttpResponseBadRequest("Bad request.")

总结

创建HttpResponse对象时,可以通过第二个参数直接设置状态码。

也可以通过修改HttpResponse对象的status_code属性来设置状态码。

使用预定义的快捷方法可以更方便地返回特定状态码的响应。

这样,你就可以灵活地控制Django应用中HTTP响应的状态码了。

相关推荐
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时1 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1231 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero071 天前
Jev 与 Laya
python·语言模型
kybs19911 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net