Tornado-cookie

时间:2023-03-08 23:55:35
Tornado-cookie

cookie

服务端在客户端的中写一个字符串,下一次客户端再访问时只要携带该字符串,就认为其是合法用户。

tornado中的cookie有两种,一种是未加密的,一种是加密的,并且可以配置生效域名、路径、过期时间。

文件目录

Tornado-cookie

Python代码

import tornado.ioloop
import tornado.web
import time class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html', ) class ManagerHandler(tornado.web.RequestHandler):
def get(self):
cookie = self.get_cookie('auth')
if cookie == '':
self.render('manager.html')
else:
self.redirect('/login') class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.render('login.html', status_text='') def post(self):
username = self.get_argument('username', None)
password = self.get_argument('password', None)
checked = self.get_argument('auto', None)
if username == 'abc' and password == '':
if checked:
self.set_cookie('usn', username, expires_days=7)
self.set_cookie('auth', expires_days=7)
else:
expire_time = time.time() + 60 * 30
# domain:针对哪个域名生效
# path:为cookie划分权限,在那一些目录下生效,默认是'/',全局生效
self.set_cookie('usn', username, expires_days=expire_time)
self.set_cookie('auth', '', expires=expire_time, path='/')
self.redirect('/manager')
else:
self.render('login.html', status_text='登陆失败') class LogoutHandler(tornado.web.RequestHandler):
def get(self):
self.set_cookie('auth', '', expires=time.time())
self.set_cookie('usn', '', expires=time.time())
self.redirect('/login') settings = {
"template_path": "views", # 配置html文件路径
"static_path": "static", # 配置静态文件路径
} # 路由映射
application = tornado.web.Application([
(r"/index", MainHandler),
(r"/login", LoginHandler),
(r"/manager", ManagerHandler),
(r"/logout", LogoutHandler) ], **settings) # 启动
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start() # session更灵活些
# set_secure_cookie有了加密,更安全

HTML页面

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/login" method="post">
<input type="text" name="username"/>
<input type="text" name="password"/>
<input type="checkbox" name="auto" value="1" >7天免登陆
<input type="submit" value="登陆"/>
<span style="color:red;">{{ status_text }}</span>
</form>
</body>
</html>

manager.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 style="color:red;">隐私页面</h1>
<h1>您的密码是123456</h1>
<h2>您的卡内余额是10000元</h2>
<a href="/logout">退出</a>
</body>
</html>

这一部分没有复杂的部分,主要涉及了tornado内cookie相关方法的应用以及设计跳转页面间的关系。