(25)Django中操作cookie与session组件(添加cookie和删除cookie)
cookie是存在于客户端浏览器上的键值对,是明文的
cookie是当用户访问网站时候和数据提起携带过去,安全性比较差, 容易被拦截
session存在于服务端的键值对,是一串加密的字符串
当用户登陆成功,session会在服务端生成一段随机的加密字符串,然后写入客户端浏览器,这样客户端浏览器每次发送请求时候都会携带这个加密字符串,然后服务端收到后进行数据库匹配,访问任何页面都会进行匹配,成功则无需登录
cookies只在当前域下有效,什么是当前域:,只要从服务端获取cookie后,访问当前域下的任何页面都不用再验证
关于render,HttpResponse,redirect都是对象,都可以实例化后调用对象下的方法
比如:写入cookie,就可以通过实例化这个对象来写入obj = HttpResponse('写入cookie成功'),删除cookie先实例化对象obj = HttpResponse('删除cookie成功'),然后调用对象下的delete方法直接删除即可obj.delete_cookie('name')
写入和获取cookie
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index),
url(r'^index/$',views.index),
url(r'^upload_file/$',views.upload_file),
url(r'^cookie_test/$',views.cookie_test),
url(r'^cookie_get/$',views.cookie_get)
]
views.py
from django.shortcuts import render,HttpResponse
from app01 import models
from django.http import JsonResponse
# Create your views here.
def index(request):
return render(request,'index.html')
def upload_file(request):
'''文件上传'''
import json
dic = {'status':100,'msg':None}
if request.method == 'POST':
# post形式上传json格式数据,POST中没有值,在body中取出
upload_dic = json.loads(request.body)
name = upload_dic['name']
pwd = upload_dic['pwd']
user = models.User.objects.filter(name=name,pwd=pwd).first()
if user:
dic['msg'] = '登陆成功'
else:
dic['status'] = 101
dic['msg'] = '账号或密码错误'
# 这里注意返回一定是Json格式
return JsonResponse(dic)
def cookie_test(request):
'''写入cookie'''
obj = HttpResponse('写入cookie成功')
#set_cookie就可以向浏览器写入cookie
obj.set_cookie('name','lqz')
obj.set_cookie('age','18')
return obj
def cookie_get(request):
'''获取cookie'''
# 这就是获取cookie的方法
name = request.COOKIES.get('name')
age = request.COOKIES.get('age')
print(name)
print(age)
obj = HttpResponse('获取cookie成功')
return obj
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
<script src="/static/jquery.js"></script>
<title>ajax</title>
</head>
<body>
<h1>Ajan实现json格式的数据传输</h1>
<p>用户名:<input type="text" name="'name" id="name"></p>
<p>密码:<input type="password" name="pwd" id="pwd"></p>
<button id="btn2">点击登录</button>
<span id="errors"></span>
</body>
<script>
$("#btn2").click(function () {
var upload_data = {name:$('#name').val(),pwd:$('#pwd').val()}
{#js语法把字典格式转成json格式字符串#}
var upload_json = JSON.stringify(upload_data)
{#js语法把json字符串转成原生的格式#}
{#var json_parse = JSON.parse(upload_data)#}
$.ajax({
url: '/upload_file/',
type: 'post',
contentType: 'application/json', //指定格式为json格式
data: upload_json,
success: function (data) {
console.log(data)
if (data.status==100){
location.href = 'http://www.baidu.com'
}else{
$('#errors').text(data.msg)
}
}
})
})
</script>
</html>
删除cookie
def cookie_del(request):
'''删除cookie'''
obj = HttpResponse('删除cookie成功')
#直接调用obj对象的delete方法删除即可
obj.delete_cookie('name')
obj.delete_cookie('age')
return obj