Django 视图

请求对象: HttpRequest 对象

get():返回字符串,如果该键对应有多个值,取出该键的最后一个值。

GET有相同的键,就把所有的值放到对应的列表里

取值格式:对象.方法。

def runoob(request):

name = request.GET.get("name")

return HttpResponse('姓名:{}'.format(name))

POST常用于 form 表单,form 表单里的标签 name 属性对应参数的键,value 属性对应参数的值

def runoob(request):

name = request.POST.get("name")

return HttpResponse('姓名:{}'.format(name))

BODY:数据类型是二进制字节流,是原生请求体里的参数内容

def runoob(request):

name = request.body

print(name)

return HttpResponse("hello")

path:获取 URL 中的路径部分,数据类型是字符串

def runoob(request):

name = request.path

print(name)

return HttpResponse("world")

method:获取当前请求的方式,数据类型是字符串,且结果为大写

def runoob(request):

name = request.method

print(name)

return HttpResponse("hello world")

响应对象:HttpResponse 对象

响应对象主要有三种形式:HttpResponse()、render()、redirect()。

HttpResponse(): 返回文本,参数为字符串,字符串中写文本内容

def runoob(request):

return HttpResponse("你好")

return HttpResponse("<a href='https://www.runoob.com/'>你好</a>")

render(): 返回文本,第一个参数为 request,第二个参数为字符串(页面名称),第三个参数为字典(可选参数,向页面传递的参数:键为页面参数名,值为views参数名)。

def runoob(request):

name ="张三"

return render(request,"runoob.html",{"name":name})

redirect()重定向,跳转新页面。参数为字符串,字符串中填写页面路径。一般用于 form 表单提交后,跳转到新页面。

def runoob(request):

return redirect("/index/")

render 和 redirect 是在 HttpResponse 的基础上进行了封装:

render:底层返回的也是 HttpResponse 对象

redirect:底层继承的是 HttpResponse 对象

相关推荐
梦想的旅途23 分钟前
企业微信API二次开发:外部群模块功能清单与全场景对接
java·python·企业微信
05664615 分钟前
Python高级——迭代器
开发语言·python·学习
猿长大人23 分钟前
C# | MediatR 入门指南:后端架构解耦
分布式·后端·架构·c#·.net
人间凡尔赛32 分钟前
Kubernetes十周年:从Cloud Native到AI Native的架构范式跃迁
后端·云原生·架构
老白干1 小时前
基于 Spring AOP 的操作日志记录:以 DeptController 增删接口为例
java·python·spring
John jj1 小时前
拆解 Telegram 群组频道收录市场:三类方案,一个可运行的评分模型,目前TG中文人工评分加模型评分机制——LetsTG收录“快速”、“无门槛”
大数据·后端·python·深度学习·搜索引擎·django·全文检索
aqi001 小时前
15天学会AI应用开发(十九)使用LangGraph实现持久记忆功能
人工智能·python·大模型·ai编程·ai应用
Boop_wu1 小时前
SpringBoot 集成阿里云短信认证服务(个人)
spring boot·后端·阿里云
月光船幽幽1 小时前
KDTree查表实现观测到动作的统计映射
python