28.Django cookie
概述
1.获取cookie
request.COOKIES['key']
request.COOKIES.get('key')
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
参数:
default: 默认值
salt: 加密盐
max_age: 后台控制过期时间
2.设置cookie
rep = HttpResponse(...) 或 rep = render(request, ...) #return的对象 rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐',...)
参数:
key, 键
value='', 值
max_age=None, 超时时间 单位秒
expires=None, 超时时间(IE requires expires, so set it if hasn't been already.) 单位日期
path='/', Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问 指定生效路径
domain=None, Cookie生效的域名
secure=False, https传输改为True
httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖
# max_age 10秒失效
result.set_cookie('username',u,max_age=10) # expires 设置失效日期
import datetime
current_date = datetime.datetime.utcnow()
current_date = current_date + datetime.timedelta(seconds=5)
result.set_cookie('username',u,expires=current_date) # 加密
obj = HttpResponse('s')
obj.set_signed_cookie('username',"kangbazi",salt="asdfasdf")
request.get_signed_cookie('username',salt="asdfasdf")
用户登录
利用cookie做用户登录,只有登录成功才能进入后台界面
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/login/" method="POST">
<input type="text" name="username" placeholder="用户名" />
<input type="password" name="pwd" placeholder="密码" />
<input type="submit" />
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎登录:{{ current_user }}</h1>
</body>
</html>
views.py
from django.shortcuts import render,HttpResponse,redirect
from django.core.handlers.wsgi import WSGIRequest
from django.utils.safestring import mark_safe user_info = {
'derek':{'pwd':''},
'jack':{'pwd':''}
} def login(request):
if request.method == 'GET':
return render(request,'login.html') if request.method == 'POST':
u = request.POST.get('username')
p = request.POST.get('pwd')
dic = user_info.get(u) #获取key的value
if not dic:
return render(request,'login.html')
if dic['pwd'] == p:
result = redirect('/index/')
result.set_cookie('username',u) #设置cookie值
#result.set_cookie('username', u, max_age=10) # 设置cookie失效时间10s
return result
else:
return render(request,'login.html') def index(request):
v = request.COOKIES.get('username')
if not v:
return redirect('/login/')
return render(request,'index.html',{'current_user':v})
另外一种设置cookie失效时间的方法
from django.shortcuts import render,HttpResponse,redirect
from django.core.handlers.wsgi import WSGIRequest
from django.utils.safestring import mark_safe user_info = {
'derek':{'pwd':''},
'jack':{'pwd':''}
} def login(request):
if request.method == 'GET':
return render(request,'login.html') if request.method == 'POST':
u = request.POST.get('username')
p = request.POST.get('pwd')
dic = user_info.get(u) #获取key的value
if not dic:
return render(request,'login.html')
if dic['pwd'] == p:
result = redirect('/index/')
result.set_cookie('username',u) #设置cookie值
#result.set_cookie('username', u, max_age=10) # 设置cookie失效时间10s
# 第二种方法 设置失效时间
import datetime
current_date = datetime.datetime.utcnow() #获取当前时间
current_date = current_date + datetime.timedelta(seconds=5)
result.set_cookie('username',u,expires = current_date)
return result
else:
return render(request,'login.html') def index(request):
v = request.COOKIES.get('username')
if not v:
return redirect('/login/')
return render(request,'index.html',{'current_user':v})
定制分页
user_list.html
<body>
<ul>
{% for item in li %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<div>
<select id='pg' onchange="ChangePageSize(this)">
<option value="10">10</option>
<option value="30">30</option>
<option value="50">100</option>
</select>
</div> <div class="pagination">
{{ page_str }}
</div> <script src="/static/jquery-1.12.4.js"></script>
<script src="/static/jquery.cookie.js"></script> <script> $(function () {
var v = $.cookie('per_page_count',{'path':'/user_list/'});
$('#pg').val(v);
}); function ChangePageSize(ths) {
var v = $(this).val();
$.cookie('per_page_count',v,{'path':'/user_list/'});
location.reload()
}
</script>
</body>
views.py
def user_list(request):
current_page = request.GET.get('p', 1)
current_page = int(current_page) per_page_count = request.COOKIES.get('per_page_count',10) #获取cookie值
per_page_count = int(per_page_count) page_obj = Page(current_page,len(LIST),per_page_count) data = LIST[page_obj.start:page_obj.end] page_str = page_obj.page_str("/user_list/") return render(request, 'user_list.html', {'li': data,'page_str': page_str})
登录认证(装饰器)
1.FBV
from django.shortcuts import render,HttpResponse,redirect
from django.core.handlers.wsgi import WSGIRequest
from django.utils.safestring import mark_safe
from django.shortcuts import reverse user_info = {
'derek':{'pwd':''},
'jack':{'pwd':''}
} def login(request):
if request.method == 'GET':
return render(request,'login.html') if request.method == 'POST':
u = request.POST.get('username')
p = request.POST.get('pwd')
dic = user_info.get(u)
if not dic:
return render(request,'login.html')
if dic['pwd'] == p:
result = redirect('/index/')
result.set_cookie('username',u)
return result
else:
return render(request,'login.html') def auth(func):
def inner(request,*args,**kwargs):
v = request.COOKIES.get('username')
if not v:
return redirect('/login/')
return func(request,*args,**kwargs)
return inner @auth
def index(request):
v = request.COOKIES.get('username')
return render(request,'index.html',{'current_user':v})
2.CBV
from django import views
from django.utils.decorators import method_decorator @method_decorator(auth, name='dispatch') # 第一种方式
class Order(views.View):
# @method_decorator(auth) #第二种方式
# def dispatch(self, request, *args, **kwargs):
# return super(Order,self).dispatch(request, *args, **kwargs) # @method_decorator(auth) #单独添加
def get(self, reqeust):
v = reqeust.COOKIES.get('username111') return render(reqeust, 'index.html', {'current_user': v}) v = reqeust.COOKIES.get('username111')
return render(reqeust, 'index.html', {'current_user': v})
28.Django cookie的更多相关文章
- Django cookie相关操作
Django cookie 的相关操作还是比较简单的 首先是存储cookie #定义设置cookie(储存) def save_cookie(request): #定义回应 response = Ht ...
- falsk 与 django cookie和session存、取、删的区别
falsk cookie的存取删需导入from flask import Flask,make_response,request# 存COOKIE的方法@app.route('/setcookie') ...
- django cookie、session
Cookie.Session简介: Cookie.Session是一种会话跟踪技术,因为http请求都是无协议的,无法记录上一次请求的状态,所以需要cookie来完成会话跟踪,Seesion的底层是由 ...
- Python之路-(Django(Cookie、分页))
Cookie 分页 1.获取Cookie: request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, sal ...
- Django Cookie 和 Sessions 应用
在Django里面,使用Cookie和Session看起来好像是一样的,使用的方式都是request.COOKIES[XXX]和request.session[XXX],其中XXX是您想要取得的东西的 ...
- Python Web框架篇:Django cookie和session
part 1 概念 在Django里面,cookie和session都记录了客户端的某种状态,用来跟踪用户访问网站的整个回话. 两者最大的区别是cookie的信息是存放在浏览器客户端的,而sessio ...
- 5.Django cookie
概述 1.获取cookie request.COOKIES['key'] request.COOKIES.get('key') request.get_signed_cookie(key, defau ...
- Django Cookie,Session
Cookie Cookie的由来 HTTP协议是无状态的,每次请求都是独立的,对服务器来说,每次的请求都是全新的,上一次的访问是数 据是无法保留到下一次的 某些场景需要状态数据或者中间数据等相关对下一 ...
- python Django cookie和session
在一个会话的多个请求中共享数据,这就是会话跟踪技术.例如在一个会话中的请求如下: 请求银行主页: 请求登录(请求参数是用户名和密码): 请求转账(请求参数与转账相关的数据): 请求信誉卡还款(请求参 ...
随机推荐
- 使用Python管理数据库
使用Python管理数据库 这篇文章的主题是如何使用Python语言管理数据库,简化日常运维中频繁的.重复度高的任务,为DBA们腾出更多时间来完成更重要的工作.文章本身只提供一种思路,写的不是很全 ...
- 基于JDK1.8的ConcurrentHashMap分析
之前看过ConcurrentHashMap的分析,感觉也了解的七七八八了.但昨晚接到了面试,让我把所知道的ConcurrentHashMap全部说出来. 然后我结结巴巴,然后应该毫无意外的话就G了,今 ...
- iterator的romove方法的注意事项
package cn.lonecloud.Iterator; import java.util.ArrayList; import java.util.Iterator; public class m ...
- 用yii2给app写接口(下)
上一节里我们讲了如何用Yii2搭建一个能够给App提供数据的API后台应用程序.那么今天我们就来探讨下授权认证和通过API接口向服务器提交数据以及如何控制API接口返回那些数据,不能返回那些数据. 授 ...
- Node.js,commonjs,require
环境: Node应用由模块组成,采用CommonJS模块规范. node的全局对象是global,没有window这个对象. process表示当前执行的进程,挂在global之下. CommonJS ...
- PAT乙级 1034
思路:是个水题,但是有坑.不能被题目忽悠了,题目保证正确的输出中没有超过整型范围的整数. 它只是保证结果不超出int,但是我们在运算过程中的乘法可能会超出int,直接把所有int改成long long ...
- 关于Spring事务的原理,以及在事务内开启线程,连接池耗尽问题.
主要以结果为导向解释Spring 事务原理,连接池的消耗,以及事务内开启事务线程要注意的问题. Spring 事务原理这里不多说,网上一搜一大堆,也就是基于AOP配合ThreadLocal实现. 这里 ...
- mysql数据库 调优
mysql调优硬件配置网络带宽mysql运行参数慢查询日志网络架构多实例(一台服务器上运行多个数据库服务)分库分表 当一台数据库服务器处理客户端的请求慢时,可能是哪些原因造成? 硬件配置低:(内存 c ...
- android WebP解析开源库-支持高清无损
在我们的项目中需要支持WebP高清无损图片,推荐一个我们已经使用的解析开源库给大家:https://github.com/keshuangjie/WebpExample/tree/master/lib ...
- DSP_TMS32F2812的串口操作
void scia_fifo_init(int ibaud) { SciaRegs.SCICCR.all =0x0007; // 1 stop bit, No loopback // No parit ...