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 ...
随机推荐
- 微博立场检测 60分Baseline
AI研习社最近举办了一个比赛--微博立场检测,实际上就是一个NLP文本分类的比赛 Baseline-FastText 我的Baseline方法用的是pkuseg分词+FastText,最好成绩是60, ...
- Spring解决循环依赖,你真的懂了吗?
导读 前几天发表的文章SpringBoot多数据源动态切换和SpringBoot整合多数据源的巨坑中,提到了一个坑就是动态数据源添加@Primary接口就会造成循环依赖异常,如下图: 这个就是典型的构 ...
- wpf 菜单样式和绑定树形数据
前言 在wpf开发中,经常会使用到Menu和ContentMenu.但是原生的样式比较简陋,对于比较追求界面美好的人来说是十分不友好的.那么,这就涉及到对Menu的样式修改了.与此同时,我们还希望Me ...
- (转)C++ 虚函数表解析
原文地址:http://blog.csdn.net/haoel/article/details/1948051 C++ 虚函数表解析 陈皓 http://blog.csdn.net/haoel 前言 ...
- Android ListView显示访问WebServices返回的JSON结果
1.WebServices的返回结果 2.ListView内容布局代码 <?xml version="1.0" encoding="utf-8"?> ...
- 分布式专题——详解Google levelDB底层原理
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是分布式专题的第10篇文章,我们继续来聊聊LSMT这个数据结构. LSMT是一个在分布式系统当中应用非常广泛,并且原理直观简单的数据结构 ...
- Oracle设置和修改system和scott的口令,并且如何连接到system和scott模式下
1.在Oracle数据库中,有个示例模式scott和系统模式system. 2.在安装数据库时只是设置了system的口令,即密码,如果忘记的话可以使用如下办法,首先打开sqlplus工具或者cmd命 ...
- hdu1908 逆序对
题目链接:https://www.luogu.com.cn/problem/P1908 这个题不要以为拿到手就可以树状数组秒,本题的数据范围是1e9显然简单的树状数组是空间不够的,点个数有5e5,所以 ...
- [阿里云-机器学习PAI快速入门与业务实战 ]课时1-机器学习背景知识以及业务架构介绍
什么是机器学习? 机器学习指的是机器通过统计学算法,对大量的历史数据进行学习从而生成经验模型,利用经验模型指导业务. 目前机器学习主要在一下一些方面发挥作用: 营销类场景:商品推荐.用户群体画像.广告 ...
- dapp 是什么?dapp 和 app 有什么区别?一文明白 dapp。
DApp 是 decentralized application 中文分布式 APP 的缩写. 一个 DApp 有后台代码运行在分布式点对点网络中.传统的 APP 的后台代码是运行在中心化的服务器. ...