cookies与session
一、cookies
-
本质:浏览器端保存的键值对
-
方便客户按照自己的习惯操作页面或软件,例如:用户验证,登陆界面,右侧菜单隐藏,控制页面列表显示条数...
-
cookies是由服务端写在浏览器端,以后每次请求的时候,浏览器都携带者cookie来访问
cookie的设置方式
-
tronado(后台设置)
- self.cookies
- self.get_cookie("k1")
- self.set_cookie("k2","v2")
-
前端js设置
- document.cookie
- document.cookie.split(“;”) 获取所有的cookie列表
- document.cookie = “k3=66” 设置
- document.cookie = “k3=66;path='/”
基本操作
后台设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get( self , * args, * * kwargs): print ( self .cookies) print ( self .get_cookie( 'k1' )) self .set_cookie( 'k2' , '999' ) self .render( 'index.html' ) settings = { 'template_path' : 'views' , } application = tornado.web.Application([ (r "/index" , MainHandler), ], * * settings) if __name__ = = "__main__" : application.listen( 8888 ) tornado.ioloop.IOLoop.instance().start() |
前端设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!DOCTYPE html> <html lang = "en" > <head> <meta charset = "UTF-8" > <title>Title< / title> < / head> <body> <script> function setCookieBySeconds(name, value, expires) { var current_date = new Date(); current_date.setDate(current_date.getSeconds() + expires); document.cookie = name + '= ' + value + ';expires=' + current_date.toUTCString(); } function setCookieByDays(name, value, expires) { var current_date = new Date(); current_date.setDate(current_date.getDate() + expires); document.cookie = name + '= ' + value + ';expires=' + current_date.toUTCString(); } / / 此外还可以导入jquery.cookie.js后通过 / / $.cookie( 'k1' , 'v1' ,{expires: 7 });设置过期时间为 7 天 < / script> < / body> < / html> |
加密cookie(签名)
cookie很容易被恶意的客户端伪造,加入你想在cookie中保存当前登陆用户的id之类的信息,你需要对cookie做签名以防止伪造,Tornado通过set_secure_cookie和get_secure_cookie方法直接支持了这种功能,要使用这些方法,你需要在创建应用一个密钥,名字为cookie_secret(在settings配置cookie_secret)
签名Cookie的本质是:
写cookie过程:
- 将值进行base64加密
- 对除值以外的内容进行签名,哈希算法(无法逆向解析)
- 拼接 签名 + 加密值
读cookie过程:
- 读取 签名 + 加密值
- 对签名进行验证
- base64解密,获取值内容
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get( self ): login_user = self .get_secure_cookie( "login_user" , None ) if login_user: self .write(login_user) else : self .redirect( '/login' ) class LoginHandler(tornado.web.RequestHandler): def get( self ): self .current_user() self .render( 'login.html' , * * { 'status' : ''}) def post( self , * args, * * kwargs): username = self .get_argument( 'name' ) password = self .get_argument( 'pwd' ) if username = = 'wupeiqi' and password = = '123' : self .set_secure_cookie( 'login_user' , '武沛齐' ) self .redirect( '/' ) else : self .render( 'login.html' , * * { 'status' : '用户名或密码错误' }) settings = { 'template_path' : 'template' , 'static_path' : 'static' , 'static_url_prefix' : '/static/' , 'cookie_secret' : 'aiuasdhflashjdfoiuashdfiuh' } application = tornado.web.Application([ (r "/index" , MainHandler), (r "/login" , LoginHandler), ], * * settings) if __name__ = = "__main__" : application.listen( 8888 ) tornado.ioloop.IOLoop.instance().start() |
二、session
-
cookie保存单一键值对,session保存多个键值对
-
cookie是保存在客户端上,session是保存在服务端
-
session是基于cookie人为构建的
-
session在服务端存储类似于字典样式的结构,可以存在全局变量,数据库,文件,memcached radis,但是不能放在局部变量里
1、面向对象基础
-
面向对象中通过索引的方式访问对象,需要内部实现__getitem__、__delitem__、__setitem__方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Foo( object ): def __getitem__( self , key): print ( '__getitem__' ,key) def __setitem__( self , key, value): print ( '__setitem__' ,key,value) def __delitem__( self , key): print ( '__delitem__' ,key) obj = Foo() result = obj[ 'k1' ] #obj['k2'] = 'wupeiqi' #del obj['k1'] |
2、Tornado扩展
- Tornado框架中,默认执行Handler的get/post等方法之前默认会执行initialize方法,所以可以通过自定义的方式使得所有请求在处理前执行操作..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class BaseHandler(tornado.web.RequestHandler): def initialize( self ): self .xxoo = "wupeiqi" class MainHandler(BaseHandler): def get( self ): print ( self .xxoo) self .write( 'index' ) class IndexHandler(BaseHandler): def get( self ): print ( self .xxoo) self .write( 'index' ) |
3、自定义session
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | import tornado.ioloop import tornado.web from hashlib import sha1 import os, time #将session以全局变量的形式保存 session_container = {} #创建cookie_str随机字符串 的函数 create_session_id = lambda : sha1( '%s%s' % (os.urandom( 16 ), time.time())).hexdigest() class Session( object ): #静态字段--session key名 session_id = "__sessionId__" def __init__( self , request): #尝试获取__sessionId__ session_value = request.get_cookie(Session.session_id) if not session_value: #获取失败,就创建随机字符串 self ._id = create_session_id() else : #成功---拿值 self ._id = session_value #最后设置cookie---"__sessionId__:随机字符串" request.set_cookie(Session.session_id, self ._id) def __getitem__( self , key): return session_container[ self ._id][key] def __setitem__( self , key, value): if session_container.has_key( self ._id): session_container[ self ._id][key] = value else : session_container[ self ._id] = {key: value} def __delitem__( self , key): del session_container[ self ._id][key] class BaseHandler(tornado.web.RequestHandler): def initialize( self ): # my_session['k1']访问 __getitem__ 方法 #实例session对象,实现索引访问 self .my_session = Session( self ) class MainHandler(BaseHandler): def get( self ): print ( self .my_session[ 'c_user' ]) print ( self .my_session[ 'c_card' ]) self .write( 'index' ) class LoginHandler(BaseHandler): def get( self ): self .render( 'login.html' , * * { 'status' : ''}) def post( self , * args, * * kwargs): username = self .get_argument( 'name' ) password = self .get_argument( 'pwd' ) if username = = 'wupeiqi' and password = = '123' : self .my_session[ 'c_user' ] = 'wupeiqi' self .my_session[ 'c_card' ] = '12312312309823012' self .redirect( '/index' ) else : self .render( 'login.html' , * * { 'status' : '用户名或密码错误' }) settings = { 'template_path' : 'views' , 'static_path' : 'static' , 'static_url_prefix' : '/static/' , 'cookie_secret' : 'aiuasdhflashjdfoiuashdfiuh' , 'login_url' : '/login' } application = tornado.web.Application([ (r "/index" , MainHandler), (r "/login" , LoginHandler), ], * * settings) if __name__ = = "__main__" : application.listen( 8888 ) tornado.ioloop.IOLoop.instance().start() |
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步