python---cookie模拟登陆和模拟session原理
cookie模拟登陆:
import tornado.web
class IndexHandler(tornado.web.RequestHandler):
def get(self):
#self.write("Hello world")
# 展示所有的cookie
# print(self.cookies)
# print(self.get_cookie('k1'))
# self.set_cookie('k1','999')#还有 过期时间 适用路径
# self.render("index.html")
if self.get_argument('u',None) in ['asd','zxc']:
self.set_secure_cookie('user',self.get_argument('u'))
else:
self.write('请登录')
class ManagerHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
#默认self.get_secure_cookie('user',None)获取的数据是bytes类型
if str(self.get_secure_cookie('user',None),encoding="utf8") in ['asd','zxc']:
self.write("欢迎登录:"+str(self.get_secure_cookie('user'),encoding="utf8"))
else:
self.redirect('/index')
settings ={
'template_path':'views',
'static_path':'statics',
'cookie_secret':'dafawafawfaw',
}
application = tornado.web.Application([
(r"/index",IndexHandler),
(r"/manager",ManagerHandler),
],**settings)
if __name__=="__main__":
application.listen(8080)
tornado.ioloop.IOLoop.instance().start()
session原理模拟(放在内存),更多是放在Redis,文件,数据库中
import tornado.web
#放在内存 redis 文件 数据库
container={}
class IndexHandler(tornado.web.RequestHandler):
def get(self):
if self.get_argument('u',None) in ['asd','zxc']:
import hashlib
import time
obj = hashlib.md5()
obj.update(bytes(str(time.time()),encoding="utf8"))
random_str = obj.hexdigest()
#这一段随机字符串需要传入到客户端cookie中,以便用户到服务端对应
container[random_str]={}
container[random_str]['k1']=123
container[random_str]['k2']=self.get_argument('u')+"parents"
container[random_str]['is_login']=True
self.set_cookie('py_session',random_str)
else:
self.write("请登录")
class ManagerHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
random_str = self.get_cookie('py_session', None)
if random_str:
if container.get(random_str,None):
if container[random_str]['is_login']: # 或者container.get(random_str,None)
self.write("欢迎登录" + container[random_str]['k2'])
return;
self.redirect("/index")
settings ={
'template_path':'views',
'static_path':'statics',
'cookie_secret':'dafawafawfaw',
}
application = tornado.web.Application([
(r"/index",IndexHandler),
(r"/manager",ManagerHandler),
],**settings)
if __name__=="__main__":
application.listen(8080)
tornado.ioloop.IOLoop.instance().start()