Django 请求与响应
目录
一、 获取请求
CS结构:client/server 客户端,服务器结构,比如安装在桌面的应用,安全性比较高,但是对客户端要求比较高。
BS结构:Browser/server 浏览器,服务器结构,方便快捷,对本地资源要求比较低,依赖网络,安全系数比较低。
在编写视图的时候,有一个默认参数 request,这个就是用来接收请求的参数,在url调用的时候自动传入值。
HTTP协议常用的请求方式
请求方式 | 描述 |
get | 明文请求,请求方便,请求数据直接写在url上,格式如下:https://www.baidu.com/s?wd=老边 以?开始,键=值&键=值 通常用来向服务器获取资源 |
post | 加密请求,请求内容不可见,安全性较高,但是用来向服务器提交数据。比如,注册,登录 |
put | 类似post,但是用来修改现有的数据,全部改。 |
delete | 类似post, 但是用来删除数据 |
options | 类似post, 但是用来修改现有的数据,改部分。 |
常用的方法:
方法 | 描述 |
COOKIES | 请求携带的cookie |
FILES | 请求携带的文件,类字典格式 |
GET | GET请求携带的内容,类字典格式 |
POST | POST请求携带的内容,类字典格式 |
body | 请求体,包含请求携带的数据 |
content_type | 请求内容类型 text/html |
get_host | 获取主机ip |
get_port | 获取主机端口 |
path | 请求地址,就是url的地址部分 |
META | 请求的具体头部参数 |
二、 表单请求
get请求
前端表单部分
<form>
<input type="text" name="search_key">
<input type="submit" value="搜索">
</form>
后端路由部分
from django.contrib import admin
from django.urls import path,re_path
from Dj.views import *
urlpatterns = [
……
path('search/', search),
……
]
后端视图部分
from Dj.models import GoodsType
def search(request):
data = request.GET.get("search_key")
t = GoodsType.objects.filter(type_name = data).first()
return render_to_response("search.html",locals())
请求步骤:
1. 输入路由进入页面
2. 输入搜索关键字执行搜索
-
输入新鲜水果,点击搜索按钮
-
因为搜索按钮是一个submit按钮,导致表单发起提交事件
-
提交的过程当中,前端检索form标签的 action和method方法
-
通过action判断提交的位置,通过method判断请求的方式
-
action默认指向当前路由,method默认是get请求方法
-
然后前端检索表单内容,以name为键 value为值进行数据整合
-
然后以method指定请求方式提交给action指向的路由,在这里就是:
-
以get请求将 search_key=新鲜水果 提交给 /search/路由
-
视图第二次由路由调用,这次request参数携带get请求传递的数据,并且通过request.GET方法转换成了<querydict{search_key: 新鲜水果}>的格式
-
通过类字典的get操作获取get请求的参数,作为条件,查询数据库,返回查询的结果到页面。
from Dj.models import GoodsType
def search(request):
#通过类字典的get操作获取get请求的参数
data = request.GET.get("search_key")
#通过get参数查询数据库,返回结果。
t = GoodsType.objects.filter(type_name = data).first()
return render_to_response("search.html",locals())
post请求
csrf攻击:跨域伪造攻击,通过跨域伪造请求身份发起请求,达到欺骗的目的。
对所有敏感信息进行加密,请求的时候会携带加密字符,凡是没有加密字符的都是无效请求,django在1.6版本后自动开启csrf保护,一般post请求没有csrf加密值,无法请求。
开启csrf校验
- 检测settings配置当中的csrf中间件。
-
使用render方法替换render_to_response方法。render和render_to_response方法类似,但是render方法第一个参数必须是request参数。
-
在前端标签之后添加csrf_token
- 后端通过request.method判断请求的方式,通过request.POST来接收post请求携带的数据。
def search(request):
if request.method == "POST":#request.method返回请求的方法类型
key = request.POST.get("search_key")
return render(request,"search.html",locals())
基于表单的图片上传和普通post请求类似,但是form表单需要有enctype属性,在视图当中需要通过request.files来接收文件信息
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="type_name">
<input type="file" name="type_picture">
<input type="submit">
</form>
from Dj.models import GoodsType
def commit(request):
"""
提交商品类型
"""
if request.method == "POST":
type_name = request.POST.get("type_name")
type_picture = request.FILES.get("type_picture")
gt = GoodsType()
gt.type_name = type_name
gt.type_picture = type_picture
gt.save()
return render(request,"commit.html",locals())
ajax请求
异步请求,ajax开启了局部提交,极大降低了服务器的压力,增强了用户体验。异步请求不会阻塞服务器。但是ajax请求本身是一种 js技术,无法返回页面,只能返回数据。
ajax是微软发明的一项页面技术,但是微软对ajax技术没有过早重视,Google公司发现并且将ajax技术发扬光大。
ajax请求只是前端的技术,在后端看了,无论是什么请求,都按照get或者post或者其他请求方式处理即可,但是ajax需要返回的数据是json格式,json是一种类字典的格式,django有专门负责返回json方法,JsonResponse,注意JsonResponse的参数必须是字典。
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/js/jquery.min.js"></script>
</head>
<body>
<input type="text" id="username" placeholder="用户名">
<span style="color: red" id="error_message"></span>
<script>
$("#username").blur(function () {
var value = $("#username").val();
$.ajax({
url: "/check_user/?username="+value,
type: "get",
data: "",
success: function (result) {
$("#error_message").text(result.data);
console.log(result)
},
error: function (error) {
console.log(error)
}
})
})
</script>
</body>
</html>
视图部分
def check_page(request):
return render_to_response("checkUser.html")
from Dj.models import User
from django.http import JsonResponse
def check_user(request):
username = request.GET.get("username")
user = User.objects.filter(username = username).first()
result = {"code": "","data": ""}
if user:
result["code"] = 500
result["data"] = "用户名重复"
else:
result["code"] = 200
result["data"] = "用户名可用"
return JsonResponse(result)
使用ajax进行含有图片的post请求提交
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/js/jquery.min.js"></script>
</head>
<body>
<input type="text" id="type_name">
<input type="file" id="type_picture">
<input type="button" value="提交" id="submit">
<script>
$("#submit").click(
function () {
var type_name = $("#type_name").val();
var type_picture = document.getElementById("type_picture").files[0];
var formdata = new FormData();
formdata.append("type_name",type_name);
formdata.append("type_picture",type_picture);
formdata.append("csrfmiddlewaretoken",'{{ csrf_token }}');
$.ajax(
{
url: "/commit_ajax/",
type: "post",
data: formdata,
processData: false, //图片上传,关闭的校验
contentType: false, //图片上传,关闭的校验
success:function (result) {
console.log(result)
},
error:function (error) {
console.log(error)
}
}
)
}
)
</script>
</body>
</html>
视图部分
from Dj.models import GoodsType
def commit_ajax(request):
"""
提交商品类型
"""
if request.method == "POST":
type_name = request.POST.get("type_name")
type_picture = request.FILES.get("type_picture")
gt = GoodsType()
gt.type_name = type_name
gt.type_picture = type_picture
gt.save()
return JsonResponse({"data":"保存成功"})
响应
响应方法 | 描述 |
HTTPResponse | 最基本的响应方式,可以直接返回字符串。 |
render_to_response | 最基本的返回页面的方法 |
render | 携带csrf_token的返回页面方法 |
JsonResponse | 返回Json数据的 |