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的更多相关文章

  1. Django之Cookie、Session、CSRF、Admin

    Django之Cookie.Session.CSRF.Admin   Cookie 1.获取Cookie: 1 2 3 4 5 6 request.COOKIES['key'] request.get ...

  2. 【python】-- Django 分页 、cookie、Session、CSRF

    Django  分页 .cookie.Session.CSRF 一.分页 分页功能在每个网站都是必要的,下面主要介绍两种分页方式: 1.Django内置分页 from django.shortcuts ...

  3. 傻傻分不清之 Cookie、Session、Token、JWT

    傻傻分不清之 Cookie.Session.Token.JWT 什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证明“你是你自己”(比如:你每天上下班打卡,都需要通过指纹打 ...

  4. 还分不清 Cookie、Session、Token、JWT?一篇文章讲清楚

    还分不清 Cookie.Session.Token.JWT?一篇文章讲清楚 转载来源 公众号:前端加加 作者:秋天不落叶 什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证 ...

  5. Cookie、Session、Token与JWT(跨域认证)

    之前看到群里有人问JWT相关的内容,只记得是token的一种,去补习了一下,和很久之前发的认证方式总结的笔记放在一起发出来吧. Cookie.Session.Token与JWT(跨域认证) 什么是Co ...

  6. [转]cookie、session、sessionid 与jsessionid

    cookie.session.sessionid 与jsessionid,要想明白他们之间的关系,下面来看个有趣的场景来帮你理解. 我们都知道银行,银行的收柜台每天要接待客户存款/取款业务,可以有几种 ...

  7. cookie、session、sessionid ,jsessionid 的区别

    本文是转载虫师博客的文章http://www.cnblogs.com/fnng/archive/2012/08/14/2637279.html cookie.session.sessionid 与js ...

  8. application、session、request、page的作用范围、Application,Session和Cookie的区别

    Web应用中的JSP和servlet都是由web服务器来调用,Jsp和Servlet之间通常不会相互调用,那么Jsp和Servlet之间交换数据就要用到application.session.requ ...

  9. cookie、session、token的区别与联系

    https://www.cnblogs.com/moyand/p/9047978.html cookie.session.token存在意义 http协议是无状态协议,请求之间是没有联系的,cooki ...

  10. 3 分钟带你深入了解 Cookie、Session、Token

    经常会有用户咨询,CDN 是否会传递 Cookie 信息,是否会对源站 Session 有影响,Token 的防盗链配置为什么总是配置失败?为此,我们就针对 Cookie.Session 和 Toke ...

随机推荐

  1. [日志分析]Graylog2进阶之获取Nginx来源IP的地理位置信息

    如果你们觉得graylog只是负责日志收集的一个管理工具,那就too young too naive .日志收集只是graylog的最最基础的用法,graylog有很多实用的数据清洗和处理的进阶用法. ...

  2. JVM 参数及各部分含义(转)

    转自:https://www.jianshu.com/p/1c6b5c2e95f9 JVM参数分类 JVM参数分为标准参数和非标准参数: 标准参数: "-"开头的参数,如-clie ...

  3. 0919-The Standard of Code Review

    The primary purpose of code review is to make sure that the overall code health of Google’s code bas ...

  4. 2. Plugin execution not covered by lifecycle configuration

    问题: 找到当前项目的工作空间下的.metadata\.plugins\org.eclipse.m2e.core路径, 然后添加lifecycle-mapping-metadata.xml文件,内容如 ...

  5. shell脚本基础-语法

    一 变量 [root@T_FOOT-Home2-ZZZ01 ~]# a=hello [root@T_FOOT-Home2-ZZZ01 ~]# echo $a hello [root@T_FOOT-Ho ...

  6. SpringMvc @Validated注解执行原理

    @Validated和@Valid对比 Spring Validation验证框架对参数的验证机制提供了@Validated(Spring's JSR-303规范,是标准JSR-303的一个变种),j ...

  7. rbac权限(2)

    models.py from django.db import models class User(models.Model): name=models.CharField(max_length=32 ...

  8. [Docker03] Deploy LNMP on Docker

    Deploy MYSQL docker pull mysql 挂载卷保存数据文件 mkdir -p /mysql/data chmod -p 777 /mysql/data MySQL使用过程中的环境 ...

  9. hdu2612 又是迷宫系列

    题目链接:http://icpc.njust.edu.cn/Problem/Hdu/2612/ 题意:有两个人在地图上不同的位置,地图上由若干个餐厅,求两人能同时到达一个餐厅所用最少的总时间. 代码如 ...

  10. java后台调用文件上传接口

    借鉴:https://blog.csdn.net/yjclsx/article/details/70675057 /** * 调用流程上传文件接口上传文件 * @param url * @param ...