day36 cookies&session
区别
1.cookies在客户端,session在服务器端
2.联系,session是人为建立的,通过cookies构建出来的,每次用户来的时候给他发一段token,下次再来的时候如果还是上次的token就认为还是上次的
分页
XSS跨站脚本攻击
csrf跨站请求伪造,用于post ,工作原理
AJAX
iframe
xmlhttprequest
jquery
$.ajax({
url:
type:
data:
dataType:
success:
error:
})
AJAX上传文件
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <input type="file" id="img" /> 9 <input type="button" onclick="UploadFile();" /> 10 <script> 11 function UploadFile(){ 12 var fileObj = $("#img")[0].files[0]; 13 var form = new FormData(); 14 form.append("k1", "v1"); 15 form.append("fff", fileObj); 16 17 $.ajax({ 18 type:'POST', 19 url: '/index', 20 data: form, 21 processData: false, // tell jQuery not to process the data 22 contentType: false, // tell jQuery not to set contentType 23 success: function(arg){ 24 console.log(arg); 25 } 26 }) 27 } 28 </script> 29 </body> 30 </html> 31 32 HTML - jQuery
2017-7-8 15:45:30
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.web import tornado.ioloop class Indexhandler(tornado.web.RequestHandler): def get(self): self.set_cookie('k1','999') ret = self.cookies print(ret) self.render('index.html') settings={ "template_path":'views' } app=tornado.web.Application({ (r'/index',Indexhandler), },**settings) if __name__=='__main__': app.listen('8888') tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="color: #c03945;">cookies</div> <script> function setCookie(name,value,expires){ var current_date = new Date(); current_date.setSeconds(current_date.getSeconds() + 5); document.cookie = name + "= "+ value +";expires=" + current_date.toUTCString(); } </script> </body> </html>
$.cookie('k1','666',{expires:7})
//这是保存七天的
var current_data=new Data();
current_data.setSeconds(current_data.getSeconds()+6)
$.cookie('k1','666',{expires:current_data})
// 这是保存6秒的
(2017-7-9 10:32:00)
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web container={} class Indexhandler(tornado.web.RequestHandler): def get(self): if self.get_argument('u',None) in ['alex','eric']: import hashlib,time obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding='utf8')) random_str=obj.hexdigest() container[random_str]={} container[random_str]['k1']=666 container[random_str]['k2']=self.get_argument('u',None)+'parents' container[random_str]['is_login']=True self.set_cookie('sess',random_str) print(container) else: self.write('please login') class Managerhandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): random_str=self.get_cookie('sess') current_uinfo=container.get(random_str,None) if not current_uinfo: self.redirect('/index') else: if current_uinfo.get('is_login',None): temp='%s--%s' %(current_uinfo.get('k1',''),current_uinfo.get('k2','')) self.write(temp) else: self.redirect('/index') settings={ 'template_path':'views' } app=tornado.web.Application([ (r'/index',Indexhandler), (r'/manager',Managerhandler), ]) if __name__=='__main__': app.listen(8888) tornado.ioloop.IOLoop.instance().start()
(2017-7-10 15:44:33)
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import hashlib, time container={} class Session: def __init__(self,handler): self.handler=handler self.random_str=None def __generate_random_str(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding='utf8')) random_str=obj.hexdigest() return random_str def set_value(self,key,value): if not self.random_str: random_str=self.handler.get_cookie('wolala') if not random_str: #random_str不存在就生成一个 #{'b7a99d741b7bd1ba2c1b64282bc93711': {'name': 'alex', 'is_login': True}} random_str=self.__generate_random_str() container[random_str]={} else: #random_str存在就 if random_str in container.keys(): pass else: random_str=self.__generate_random_str() container[random_str]={} self.random_str=random_str container[self.random_str][key]=value self.handler.set_cookie('wolala',self.random_str) def get_value(self,key): random_str=self.handler.get_cookie('wolala') print('random_str',random_str) if not random_str: return None user_info_dict=container.get(random_str,None) if not user_info_dict: return None value=user_info_dict.get(key,None) return value class Indexhandler(tornado.web.RequestHandler): def get(self): if self.get_argument('u',None) in ['alex','eric']: s=Session(self) s.set_value('is_login',True) s.set_value('name',self.get_argument('u',None)) print(container) self.write('has logined') else: self.write('please login') class Managerhandler(tornado.web.RequestHandler): def get(self): s=Session(self) val=s.get_value('is_login') # print(1, val,s.get_value('name')) if val : self.write(s.get_value('name')) else: self.write('failure') settings={ 'template_path':'views' } app=tornado.web.Application([ (r'/index',Indexhandler), (r'/manager',Managerhandler), ]) if __name__=='__main__': app.listen(8888) tornado.ioloop.IOLoop.instance().start()
2017-7-10 16:18:00
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import hashlib, time container={} class Basehandler(tornado.web.RequestHandler): def __init__(self): self.session=Session(self) class Session: def __init__(self,handler): self.handler=handler self.random_str=None def __generate_random_str(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding='utf8')) random_str=obj.hexdigest() return random_str def __setitem__(self, key, value): random_str=self.handler.get_cookie('wolala') if not random_str: #random_str不存在就生成一个 #{'b7a99d741b7bd1ba2c1b64282bc93711': {'name': 'alex', 'is_login': True}} random_str=self.__generate_random_str() container[random_str]={} else: #random_str存在就 if random_str in container.keys(): pass else: random_str=self.__generate_random_str() container[random_str]={} self.random_str=random_str container[self.random_str][key]=value self.handler.set_cookie('wolala',self.random_str) def __getitem__(self,key): random_str=self.handler.get_cookie('wolala') print('random_str',random_str) if not random_str: return None user_info_dict=container.get(random_str,None) if not user_info_dict: return None value=user_info_dict.get(key,None) return value class Indexhandler(Basehandler): def get(self): if self.get_argument('u',None) in ['alex','eric']: self.session['is_login']=True self.session['name']=self.get_argument('u',None) print(container) self.write('has logined') else: self.write('please login') class Managerhandler(Basehandler): def get(self): val=self.session['is_login'] if val : self.write(self.session['name']) else: self.write('failure') settings={ 'template_path':'views' } app=tornado.web.Application([ (r'/index',Indexhandler), (r'/manager',Managerhandler), ]) if __name__=='__main__': app.listen(8888) tornado.ioloop.IOLoop.instance().start()
更正session(2017-7-12 14:10:22)
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import hashlib, time container={} class Basehandler(tornado.web.RequestHandler): def initialize(self): self.session=Session(self) class Session: def __init__(self,handler): self.handler=handler self.random_str=None def __generate_random_str(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding='utf8')) random_str=obj.hexdigest() return random_str def __setitem__(self, key, value): random_str=self.handler.get_cookie('wolala') if not random_str: #random_str不存在就生成一个 #{'b7a99d741b7bd1ba2c1b64282bc93711': {'name': 'alex', 'is_login': True}} random_str=self.__generate_random_str() container[random_str]={} else: #random_str存在就 if random_str in container.keys(): pass else: random_str=self.__generate_random_str() container[random_str]={} self.random_str=random_str container[self.random_str][key]=value self.handler.set_cookie('wolala',self.random_str) def __getitem__(self,key): random_str=self.handler.get_cookie('wolala') if not random_str: return None user_info_dict=container.get(random_str,None) if not user_info_dict: return None value=user_info_dict.get(key,None) return value class Indexhandler(Basehandler): def get(self): print('get') if self.get_argument('u',None) in ['alex','eric']: self.session['is_login']=True print('islogin') self.session['name']=self.get_argument('u',None) print(container) self.write('has logined') else: self.write('please login') class Managerhandler(Basehandler): def get(self): val=self.session['is_login'] if val : self.write(self.session['name']) else: self.write('failure') settings={ 'template_path':'views' } app=tornado.web.Application([ (r'/index',Indexhandler), (r'/manager',Managerhandler), ]) if __name__=='__main__': app.listen(8888) tornado.ioloop.IOLoop.instance().start()
验证码(2017-7-12 14:10:05)
要install pillow module
并且把checkcode.py 放在里面
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import hashlib, time container={} class Basehandler(tornado.web.RequestHandler): def initialize(self): self.session=Session(self) class Session: def __init__(self,handler): self.handler=handler self.random_str=None def __generate_random_str(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding='utf8')) random_str=obj.hexdigest() return random_str def __setitem__(self, key, value): random_str=self.handler.get_cookie('wolala') if not random_str: #random_str不存在就生成一个 #{'b7a99d741b7bd1ba2c1b64282bc93711': {'name': 'alex', 'is_login': True}} random_str=self.__generate_random_str() container[random_str]={} else: #random_str存在就 if random_str in container.keys(): pass else: random_str=self.__generate_random_str() container[random_str]={} self.random_str=random_str container[self.random_str][key]=value self.handler.set_cookie('wolala',self.random_str) def __getitem__(self,key): random_str=self.handler.get_cookie('wolala') print('random_str',random_str) if not random_str: return None user_info_dict=container.get(random_str,None) if not user_info_dict: return None value=user_info_dict.get(key,None) return value class Indexhandler(Basehandler): def get(self): if self.get_argument('u',None) in ['alex','eric']: self.session['is_login']=True self.session['name']=self.get_argument('u',None) print(container) self.write('has logined') else: self.write('please login') class Managerhandler(Basehandler): def get(self): val=self.session['is_login'] if val : self.write(self.session['name']) else: self.write('failure') class Loginhandler(Basehandler): def get(self): self.render('login.html',statu='') def post(self, *args, **kwargs): user=self.get_argument('user',None) pwd=self.get_argument('password',None) security=self.get_argument('security',None) print(security,'secu') checkcode=self.session['security'] if security.upper()==checkcode.upper(): self.write('correct') else: self.render('login.html',statu='wrong code') class Checkcodehandler(Basehandler): def get(self, *args, **kwargs): import io import check_code mstream=io.BytesIO() img,code=check_code.create_validate_code() img.save(mstream,'GIF') self.write(mstream.getvalue()) self.session['security']=code print(container) settings={ 'template_path':'views' } app=tornado.web.Application([ (r'/index',Indexhandler), (r'/manager',Managerhandler), (r'/login',Loginhandler), (r'/check_code',Checkcodehandler), ],**settings) if __name__=='__main__': app.listen(8888) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> <p><input name='user' type="text" placeholder="user"> </p> <p><input name="password" type="text" placeholder="password"> </p> <p><input name="security" type="text" placeholder="security"> <img src="/check_code" onclick="Changecode();" id="imgcode"></p> <input type="submit" value="submit"> <span>{{statu}}</span> </form> <script> function Changecode() { var code=document.getElementById('imgcode'); code.src+='?' } </script> </body> </html>
Ajax跨域请求(2017-7-13 11:16:04)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/xsrf" method="post"> <span>{% raw xsrf_form_html() %}</span> <!--这样可以隐藏这个数据--> </form> <button value="aj xsrf" onclick="Xsrf();">submit</button> <input type="submit" value="submittt"> <script src="/statics/jquery-3.1.1.js"></script> <script> function getCookie(name) { var r = document.cookie.match("\\b" + name + "=([^;]*)\\b"); return r ? r[1] : undefined; } function Xsrf() { var nid=getCookie('_xsrf'); $.post({ url:'/xsrf', data:{'k1':'v1','_xsrf':nid}, success:function (callback) { // 发送成功后自动执行内容 // callback会返回服务器write的数据 console.log(callback) } }) } </script> </body> </html>
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import hashlib, time container={} class Basehandler(tornado.web.RequestHandler): def initialize(self): self.session=Session(self) class Session: def __init__(self,handler): self.handler=handler self.random_str=None def __generate_random_str(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding='utf8')) random_str=obj.hexdigest() return random_str def __setitem__(self, key, value): random_str=self.handler.get_cookie('wolala') if not random_str: #random_str不存在就生成一个 #{'b7a99d741b7bd1ba2c1b64282bc93711': {'name': 'alex', 'is_login': True}} random_str=self.__generate_random_str() container[random_str]={} else: #random_str存在就 if random_str in container.keys(): pass else: random_str=self.__generate_random_str() container[random_str]={} self.random_str=random_str container[self.random_str][key]=value self.handler.set_cookie('wolala',self.random_str) def __getitem__(self,key): random_str=self.handler.get_cookie('wolala') print('random_str',random_str) if not random_str: return None user_info_dict=container.get(random_str,None) if not user_info_dict: return None value=user_info_dict.get(key,None) return value class Indexhandler(Basehandler): def get(self): if self.get_argument('u',None) in ['alex','eric']: self.session['is_login']=True self.session['name']=self.get_argument('u',None) print(container) self.write('has logined') else: self.write('please login') class Managerhandler(Basehandler): def get(self): val=self.session['is_login'] if val : self.write(self.session['name']) else: self.write('failure') class Loginhandler(Basehandler): def get(self): self.render('login.html',statu='') def post(self, *args, **kwargs): user=self.get_argument('user',None) pwd=self.get_argument('password',None) security=self.get_argument('security',None) print(security,'secu') checkcode=self.session['security'] if security.upper()==checkcode.upper(): self.write('correct') else: self.render('login.html',statu='wrong code') class Checkcodehandler(Basehandler): def get(self, *args, **kwargs): import io import check_code mstream=io.BytesIO() img,code=check_code.create_validate_code() img.save(mstream,'GIF') self.write(mstream.getvalue()) self.session['security']=code print(container) #给他写一个类 class Csrfhandler(Basehandler): def get(self): self.render('xsrf.html') def post(self, *args, **kwargs): #只能用post的方式提交 self.write('seeing directry') settings={ 'template_path':'views', 'xsrf_cookies':True , # 'static_path':'statics', 'static_url_prefix':'/statics/' } app=tornado.web.Application([ (r'/index',Indexhandler), (r'/manager',Managerhandler), (r'/login',Loginhandler), (r'/check_code',Checkcodehandler), (r'/xsrf',Csrfhandler),#在这里要加这个 ],**settings) if __name__=='__main__': app.listen(8888) tornado.ioloop.IOLoop.instance().start()
上传文件(2017-7-14 15:20:54)
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.web import tornado.ioloop class Indexhandler(tornado.web.RequestHandler): def get(self): self.set_cookie('k1','999') ret = self.cookies print(ret) self.render('ajaxindex.html') def post(self, *args, **kwargs): print(self.get_argument('user')) print(self.get_arguments('fa')) self.write('ssssssssss') file_data=self.request.files["fff"] print(file_data) for f in file_data: file_name=f['filename'] with open(file_name,'wb') as fw: fw.write(f['body']) settings={ "template_path":'views', "static_url_prefix":'/statics/', } app=tornado.web.Application({ (r'/index',Indexhandler), },**settings) if __name__=='__main__': app.listen('8888') tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/index" method="POST" enctype="multipart/form-data"> <!--发送文件要写enctype="multipart/form-data"--> <input type="text" name="user"> <h3>hobbit</h3> <input name="fa" value="1" type="checkbox">basketball <input name="fa" value="2" type="checkbox">football <input name="fa" value="3" type="checkbox">glassball <input type="submit" value="sub"> <input type="file" name="fff"> </form> <p> <input type="button" onclick="Xmlsendrequest();" value="ajaxrequest"> </p> <script type="text/javascript" src="/statics/jquery-3.1.1.js"></script> <script> function Xmlsendrequest() { $.ajax({ }) } </script> </body> </html>
iframe兼容性更好的上传文件(2017-7-14 16:07:32)
#! bin/usr/evn python # -*- coding:utf-8 -*- import tornado.web import tornado.ioloop class Indexhandler(tornado.web.RequestHandler): def get(self): self.render('iframeupload.html') def post(self, *args, **kwargs): file_data=self.request.files["fff"] print(file_data) for f in file_data: file_name=f['filename'] with open(file_name,'wb') as fw: fw.write(f['body']) settings={ "template_path":'views', "static_url_prefix":'/statics/', # 'static_path':'statics' } app=tornado.web.Application({ (r'/index',Indexhandler), },**settings) if __name__=='__main__': app.listen('8888') tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } </style> </head> <body> <form id="my_form" name="form" action="/index" method="POST" enctype="multipart/form-data" > <div id="main"> <input name="fff" id="my_file" type="file" /> <input type="button" name="action" value="Upload" onclick="redirect()"/> <iframe id='my_iframe' name='my_iframe' src="" class="hide"></iframe> </div> </form> <script src="/statics/jquery-3.1.1.js"></script> <script> function redirect(){ // document.getElementById('my_iframe').onload = Testt; document.getElementById('my_form').target = 'my_iframe'; document.getElementById('my_form').submit(); } // function Testt(ths){ // var t = $("#my_iframe").contents().find("body").text(); // console.log(t); // } </script> </body> </html>