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. Button相关设置

    2020-03-11 每日一例第4天 1.添加按钮1-6,并修改相应的text值:  2.窗体Load事件加载代码: private void Form1_Load(object sender, Ev ...

  2. python从数据库取数据后写入excel 使用pandas.ExcelWriter设置单元格格式

    用python从数据库中取到数据后,写入excel中做成自动报表,ExcelWrite默认的格式一般来说都比较丑,但workbook提供可以设置自定义格式,简单记录个demo,供初次使用者参考. 一. ...

  3. 【简说Python WEB】Flask-Moment

    目录 [简说Python WEB]Flask-Moment 系统环境:Ubuntu 18.04.1 LTS Python使用的是虚拟环境:virutalenv Python的版本:Python 3.6 ...

  4. Socket编程简介

    目录 背景 基础 流程 参考 本文系读书笔记,非深入研究,也无代码,如非所需,请见谅. 哦,这里有份不错的:Linux的SOCKET编程详解 背景 花了好久的时间(大约一周,我太垃圾)看完了一篇英文文 ...

  5. Uniapp使用GoEasy实现websocket实时通讯

    Uniapp作为近来最火的移动端开发技术,一套代码,可以打包成Android/iOS app和各种平台的小程序,可谓是没有最方便只有更方便. GoEasy上架DCloud Uniapp插件市场已经有一 ...

  6. [极客大挑战 2019]PHP1

    知识点:PHP序列化与反序列化,最下方有几个扩展可以看一下 他说备份了,就肯定扫目录,把源文件备份扫出来 dirsearch扫目录扫到www.zip压缩包

  7. Hive常用的10个系统函数及作用

    聚合函数 函数处理的数据粒度为多条记录. sum()—求和 count()—求数据量 avg()—求平均直 distinct—求不同值数 min—求最小值 max—求最人值 分析函数 Analytic ...

  8. python txt文件批处理

    首先,切换文件路径到所在文件夹 然后,将txt文件内容按行读取,写入到all.txt def txtcombine(): files=glob.glob('*.txt') all = codecs.o ...

  9. Building Applications with Force.com and VisualForce(六):Designing Applications for Multiple users: Accommodating Multiple Users in your App

    Dev 401-006 Designing Applications for Multiple users: Accommodating Multiple Users in your App. Cou ...

  10. [Java网络安全系列面试题] 说一说TCP和UDP的区别与联系?

    TCP TCP是Transfer Control Protocol(传输控制协议)的简称,是一种面向连接的保证可靠传输的协议. 在TCP/IP协议中,IP层主要负责网络主机的定位,数据传输的路由,由I ...