使用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有效时间

      

 

                         

posted @ 2017-03-13 22:37  Jhon23  阅读(258)  评论(0编辑  收藏  举报