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 对象

相关推荐
代码什么用1 小时前
Spring基础使用
java·后端·spring
明月_清风1 小时前
Deno 终局来了:从挑战 Node 到被 Cloudflare 收编
前端·后端·node.js
蜗牛互联网2 小时前
Java 17 HttpClient调用文件转写API的超时与失败回退
java·人工智能·后端
全栈练习生2 小时前
AI Agent 沙箱
python·ai
SEO_juper3 小时前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站
用户69371750013844 小时前
2026,程序员的时代拐点到了
android·前端·后端
惜鸟4 小时前
从源码看 pi 的上下文管理:原始数据永久保留,模型视角按需裁剪
后端
量化分析码农4 小时前
【Python量化策略评估体系 #05】极端行情扛得住吗?2008/2015/2020 三场景压力测试
后端
十年Java程序媛4 小时前
Java 接口和抽象类对比|Java8 新特性,抛弃老旧八股,正确选型
java·spring boot·后端
IT_陈寒4 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端