使用tornado框架简单记录浏览器cookie

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()


运行结果:






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值