Views->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="password" name="password">
<input type="checkbox" name="auto" value="1">7天免登录
<input type="submit" value="登录">
<span style="color: red">{{status_text}}</span>
</form>
</body>
</html>
Views->manager.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/logout">退出</a>
<h1>银行卡余额:-1000</h1>
</body>
</html>
Views->index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>cookie</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>
index.py
import tornado.ioloop
import tornado.web
import time
class IndexHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.render('index.html')
class LoginHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.render('login.html', status_text="")
def post(self, *args, **kwargs):
username = self.get_argument('username', None)
pwd = self.get_argument('password', None)
check = self.get_argument('auto', None)
if username == 'alex' and pwd == 'sb':
if check:
self.set_cookie('auth','1',expires_days=7)
else:
r = time.time() + 10
self.set_cookie('auth', '1', expires=r)
self.redirect('/manager')
else:
self.render('login.html', status_text="登录失败")
class ManagerHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
co = self.get_cookie('auth')
if co == '1':
self.render('manager.html')
else:
self.redirect('/login')
class LogoutHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.set_cookie('auth', '0')
self.redirect('/login')
settings = {
"template_path": "views", # 模板路径的配置
}
application = tornado.web.Application([
(r"/index", IndexHandler),
(r"/login", LoginHandler),
(r"/manager", ManagerHandler),
(r"/logout", LogoutHandler),
], **settings)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
运行结果: