使用cookie进行登录的小案例

本文介绍使用Python的Tornado Web框架实现用户登录、登出及权限验证等功能,并演示了如何通过设置Cookie进行用户状态管理。
#!/usr/bin/env python
# -*- coding:utf-8-*-


import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):

    def get(self):
        self.render('index.html')

class LoginHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.render('login.html', status="")

    def post(self, *args, **kwargs):
        username = self.get_argument("username")
        password = self.get_argument("password")
        if username == 'haha' and password == '123':
            self.set_cookie('auth', '1')
            self.redirect('/manager')
        else:
            self.render('login.html', status="登录失败")


class ManagerHandler(tornado.web.RequestHandler):

    def get(self):
        coo = self.get_cookie("auth")
        if coo == "1":
            self.render('manager.html')
        else:
            self.render('login.html',status='')


class LogoutHandler(tornado.web.RequestHandler):

    def get(self):
        self.set_cookie("auth", "3", expires_days=4)
        self.render('login.html', status='')

settings = {
    'template_path': 'views',

     }

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()
denglu.py

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h>银行余额</h>
<a href="/logout">logout</a>
</body>
</html>
manager.py

 

<!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="submit" value="login"/>
       <span style="color: red">{{status}}</span>
  </form>
</body>
</html>
login.html

 

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

 

知识点归纳:1、get_argument()#得到表单的输入值

                 2、set_cookie() &get_cookie()#设置和得到cookie

      3、self.redirect()#跳转某一页

                 4、self.render()#渲染,注意参数一一对应

                 5、set_cookie(,expires_days=4)#设置cookie有效时间

      

 

                         

转载于:https://www.cnblogs.com/yongliang/p/6545471.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值