cookie、session、csrf
cookie的设置和获取
import time
from tornado.web import RequestHandler class IndexHandle(RequestHandler):
def get(self):
# 设置cookie
self.set_cookie('username', 'ivy')
# 设置过期时间为60s
self.set_cookie('username', 'ivy', expires=time.time() + 60)
# 设置过期时间为2天
self.set_cookie('username', 'ivy', expires_days=2)
# 当httponly为True时,网页的js代码无法获取该cookie
self.set_cookie('username', 'ivy', httponly=True)
# 设置cookie的过期时间为2分钟,max_age的优先级大于expires
self.set_cookie('username', 'ivy', max_age=120, expires=time.time() + 60)
# 设置加密的cookie,设置加密必须到app的里面去新增一个cookie_secret的参数,让这个参数等于一个字符串(盐)
self.set_secure_cookie('username', 'ivy') # 获取cookie
self.get_cookie('ivy')
# 获取加密的cookie, 返回字节数据
self.get_secure_cookie('username')
登录验证
from tornado.web import RequestHandler, Application, authenticated
from tornado.httpserver import HTTPServer
from tornado.options import options, define
from tornado.ioloop import IOLoop
from util import uimethods, uimodules define('port', default=7981, type=int) class BaseHandle(RequestHandler):
def get_current_user(self):
current_user = self.get_secure_cookie('username')
if current_user:
return current_user
return None class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.render('index.html') class LoginHandle(RequestHandler):
def get(self):
self.render('login.html') def post(self):
username = self.get_argument('username')
password = self.get_argument('password')
if username == password:
self.set_cookie(username, password)
self.write('登录成功!') application = Application(
handlers=[
(r'/index', IndexHandle),
(r'/login', LoginHandle),
],
template_path='templates',
ui_methods=uimethods,
ui_modules=uimodules,
login_url='/login',
) if __name__ == '__main__':
options.parse_command_line()
app = HTTPServer(application)
app.listen(options.port)
IOLoop.current().start()
- 在登录成功之后设置cookie
- 新建base类,重写get_current_user方法
- get_current_user:当当前的cookie中有特定的值的时候,返回该值
- 导入authenticated方法
- 在需要检测时候登录的方法页面调用该函数(装饰器的方法)
- 在app里面配置一条login_url的参数,当检测到未登录的时候(get_current_user返回None)就让页面跳转到该路由下
验证登录后跳转回原页面
from tornado.web import RequestHandler, authenticated class BaseHandle(RequestHandler):
def get_current_user(self):
current_user = self.get_cookie('login')
if current_user:
return current_user class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.write('index 页面') class LoginHandle(BaseHandle):
def get(self):
next_url = self.get_argument('next', '')
self.render('login.html', next_url=next_url) def post(self):
username = self.get_argument('username', '')
password = self.get_argument('password', '')
next_url = self.get_argument('next', '')
if username == password and next_url:
self.set_secure_cookie('login', 'true')
self.redirect(next_url)
elif username == password:
self.set_secure_cookie('login', 'true')
self.write('登录成功!')
from tornado.web import Application
from tornado.options import options
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import handles settings = {
'template_path': 'templates',
'static_path': 'static',
'cookie_secret': 'summer',
'login_url': '/login' } urlpatterns = [
(r'/login', handles.LoginHandle),
(r'/index', handles.IndexHandle),
] app = Application(handlers=urlpatterns, **settings) if __name__ == '__main__':
options.parse_command_line()
http = HTTPServer(app)
http.listen(80)
IOLoop.current().start()
- 当用户未登录直接访问index页面的时候,因为配置了验证登录(authenticated),所以他会直接跳转到login_url,并且url附带next参数
- 在登录页面获取这个next参数,如果没有默认为空,将这个参数传到页面的action中
- 在form表单提交后,在post方法里获取这个next参数,如果用户名和密码正确,并且存在这个next参数,就直接跳转到next参数所指向的url
- 若没有,就跳到正常登陆页面。
Session
- 使用前的配置:
- pip install redis
- pip install pycket
- settings配置:
from tornado.web import Application
from tornado.options import options
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import handles settings = {
'template_path': 'templates',
'static_path': 'static',
'cookie_secret': 'summer',
'login_url': '/login',
'pycket': {
'engine': 'redis',
'storage': {
'host': 'localhost',
'port': 6379,
'db_sessions': 6,
'db_notifications': 11,
'max_connections': 3 * 10,
},
'cookies': {
'expires_days': 7,
'max_age': 100
},
},
} urlpatterns = [
(r'/login', handles.LoginHandle),
(r'/index', handles.IndexHandle),
] app = Application(handlers=urlpatterns, **settings) if __name__ == '__main__':
options.parse_command_line()
http = HTTPServer(app)
http.listen(1996)
IOLoop.current().start()如果redis有密码,在配置项里加一个password就可以了
- 使用:
from tornado.web import RequestHandler, authenticated
from pycket.session import SessionMixin class BaseHandle(RequestHandler, SessionMixin):
def get_current_user(self):
current_user = self.session.get('login')
if current_user:
return current_user class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.write('index 页面') class LoginHandle(BaseHandle):
def get(self):
next_url = self.get_argument('next', '')
self.render('login.html', next_url=next_url) def post(self):
username = self.get_argument('username', '')
password = self.get_argument('password', '')
next_url = self.get_argument('next', '')
if username == password and next_url:
self.session.set('login', 'true')
self.redirect(next_url)
elif username == password:
self.set_secure_cookie('login', 'true')
self.write('登录成功!') - 导入SessionMinxin
- 让BaseHandle继承自SessionMinxin
- 设置session
- self.session.set(key, value)
- 获取session
- self.session.get(key)
xsrf:
在form表单的html里面加入{% module xsrf_form_html() %}即可
cookie、session、csrf的更多相关文章
- Django之Cookie、Session、CSRF、Admin
Django之Cookie.Session.CSRF.Admin Cookie 1.获取Cookie: 1 2 3 4 5 6 request.COOKIES['key'] request.get ...
- 【python】-- Django 分页 、cookie、Session、CSRF
Django 分页 .cookie.Session.CSRF 一.分页 分页功能在每个网站都是必要的,下面主要介绍两种分页方式: 1.Django内置分页 from django.shortcuts ...
- 傻傻分不清之 Cookie、Session、Token、JWT
傻傻分不清之 Cookie.Session.Token.JWT 什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证明“你是你自己”(比如:你每天上下班打卡,都需要通过指纹打 ...
- 还分不清 Cookie、Session、Token、JWT?一篇文章讲清楚
还分不清 Cookie.Session.Token.JWT?一篇文章讲清楚 转载来源 公众号:前端加加 作者:秋天不落叶 什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证 ...
- Cookie、Session、Token与JWT(跨域认证)
之前看到群里有人问JWT相关的内容,只记得是token的一种,去补习了一下,和很久之前发的认证方式总结的笔记放在一起发出来吧. Cookie.Session.Token与JWT(跨域认证) 什么是Co ...
- [转]cookie、session、sessionid 与jsessionid
cookie.session.sessionid 与jsessionid,要想明白他们之间的关系,下面来看个有趣的场景来帮你理解. 我们都知道银行,银行的收柜台每天要接待客户存款/取款业务,可以有几种 ...
- cookie、session、sessionid ,jsessionid 的区别
本文是转载虫师博客的文章http://www.cnblogs.com/fnng/archive/2012/08/14/2637279.html cookie.session.sessionid 与js ...
- application、session、request、page的作用范围、Application,Session和Cookie的区别
Web应用中的JSP和servlet都是由web服务器来调用,Jsp和Servlet之间通常不会相互调用,那么Jsp和Servlet之间交换数据就要用到application.session.requ ...
- cookie、session、token的区别与联系
https://www.cnblogs.com/moyand/p/9047978.html cookie.session.token存在意义 http协议是无状态协议,请求之间是没有联系的,cooki ...
- 3 分钟带你深入了解 Cookie、Session、Token
经常会有用户咨询,CDN 是否会传递 Cookie 信息,是否会对源站 Session 有影响,Token 的防盗链配置为什么总是配置失败?为此,我们就针对 Cookie.Session 和 Toke ...
随机推荐
- Docker深入浅出系列 | Swarm多节点实战
目录 前期准备 Swarm基本概念 什么是Docker Swarm 为什么要用Swarm Swarm的网络模型 Swarm的核心实现机制 服务发现机制 负载均衡机制Routing Mesh Docke ...
- git命令,github网站以及sourceTree用法详解
1.git下载安装 这里只是windows安装方法: 进入这个网址:http://msysgit.github.com/,点击下载,就会下载下来一个exe文件,双击打开,安装即可 完成安装之后,就可以 ...
- seldom之数据驱动
seldom之数据驱动 如果自动化某个功能,测试数据不一样而操作步骤是一样的,那么就可以使用参数化来节省测试代码. seldom是我在维护一个Web UI自动化测试框,这里跟大家分享seldom参数化 ...
- vue-element框架通过blob进行后端token权限验证下载
在项目中,后端要求下载时要进行后端的权限验证,发现a链接进行直接下载无法满足这个需求,只能通过blob对象来进行下载操作,翻阅大量资料最后实现该功能.以下是我个人的理解,如有不足,请各位大佬多指教 / ...
- shell脚本基础-四种启动方式
1.当前路径启动 ./test.sh 2.绝对路径启动 pwd /data/beijing 'pwd'/test.sh 3.指定解释器执行 sh test.sh bash test.sh 4.shel ...
- Selenium系列(一) - 8种元素定位方式的详细解读
安装Selenium和下载Driver 安装selenium pip3 install selenium -i http://pypi.douban.com/simple --trusted-hos ...
- Servlet(简介,请求参数,页面跳转,生命周期,创建,配置,ServletContext,线程)
1.Servlet简介 servlet是java servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序, 主要功能在于交互式浏览和修改数据,生成动态的web内容 服务端运行的 ...
- Java第十三周实验作业
实验十三 图形界面事件处理技术 实验时间 2018-11-22 1.实验目的与要求 (1) 掌握事件处理的基本原理,理解其用途: 事件源:能够产生事件的对象都可以成为事件源,如文本框.按钮等,一个事 ...
- java获取近几天的日期
最近在写接口的时候老遇见从mysql中获取近几天数据的需求,获取日期这块不是很熟,网上看了很多但是代码量都太大,还是问了下别人,写了三行代码就解决了,不多说 贴代码了 下面是我获取近十天,每天的日期: ...
- Java导出Excel文件
/** * 导出 用get请求 * @param response * @param * @throws IOException */ @RequestMapping(value = "/d ...