美文网首页
用户登录和登出功能的实现(十五)

用户登录和登出功能的实现(十五)

作者: 梦捷者 | 来源:发表于2020-04-15 08:58 被阅读0次

    一、基本步骤框架如下:

    1、增加 models(User),执行 alembic 更新数据库或者执行SQL创建对应的表
    2、增加 utils 辅助函数 user_login
    3、调用 authenticate,完成登录,编写相应的前端代码
    4、编写退出类来进行用户退出处理

    二、用户登录功能实现如下:

    1、编写相关出处理get/post方法的登录类(在main.py模块中进行)

    class LoginHandler(BaseHandler):
        def get(self):
            next_url = self.get_argument('next', '/')
            print(next_url)
            if self.current_user:
                print("此时的session对应的值为{}".format(self.current_user))
                self.redirect(next_url)
            else:
                self.render('user/login.html', next_url=next_url,msg="暂时无问题!!")
            # if self.get_cookie("define_cookie"):
            #     username = self.get_cookie("define_cookie")
            #     session = Session()
            #     users = session.query(User.id, User.username, User.gender, User.age, User.creatime, User.emial,).all()
            #     self.render('user/information.html', username=username, users=users)
            # else:
            #     self.render('user/login.html')
    
        def post(self):
            next_url = self.get_argument('next_url', '/')
            username = self.get_argument("username", '')
            password = self.get_argument("password", '')
            ret = user_login(username, password)
            if ret is not None:
                # if not self.get_cookie("define_cookie"):
                #     self.set_cookie("define_cookie", username)
                #     if  value == True:
                #         session = Session()
                #         users = session.query(User.id, User.username, User.gender, User.age, User.creatime, User.emial,).all()
                #         self.render('user/information.html', users=users, username =username)
                #     else:
                #         self.write('出现{}'.format(value))
                if not self.session.get('username_session'):
                    if ret['result'] == True:
                        self.session.set("username_session", username)
                        # session = Session()
                        # users = session.query(User.id, User.username, User.gender, User.age, User.creatime, User.emial,).all()
                        # self.render('user/information.html', users=users, username=username)
                        self.redirect(next_url)
                    else:
                        self.render('user/login.html', next_url=next_url, msg=ret['msg'])
            else:
                self.render('user/login.html', next_url=next_url, msg='用户名不存在')
    

    2、编写user_login函数来进行用户登录的相关逻辑

    def user_login(username, password):
        """
        用户登录模块
        :param username:
        :param password:
        :return:
        """
        try:
            ret = {'result': False}
            if username and password:
                session = Session()
                user = session.query(User).filter_by(username=username).first()
                session.close()
                # if hash(session.query(User.password).filter(User.username == username).first()[0]) == hash(password):
                if hash(user.password) == hash(password):
                    ret['result'] = True
                else:
                    ret['msg'] = '密码错误'
            else:
                ret['msg'] = '用户名和密码不能为空'
            return ret
        except:
            pass
    
    

    3、再写入相关的路由

    handlers=  [(r'/login', main.LoginHandler),]
    

    4、编写前端代码

    <!DOCTYPE html>
    <html lang="zh-CN" >
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="../../static/upload/hu.ico">
        <title>用户登录</title>
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <link href="../../static/css/signin.css" rel="stylesheet">
      </head>
      <body background="../../static/upload/dog.jpg">
    
        <div class="container" >
    
          <form class="form-signin" action="/login" enctype="multipart/form-data" method="post">
              {% if msg!= None%}
              <h4 style="margin-left: 75px;color: #ff6600">{{ msg }}</h4>
              {% end %}
            <h2 class="form-signin-heading" style="margin-left: 45px">请你进行登录</h2>
               <label for="inputusername" class="sr-only">用户名</label>
            <input type="text" id="inputusername" class="form-control" placeholder="请填写用户名" required autofocus name="username">
            <label for="inputPassword" class="sr-only">密码</label>
            <input type="password" id="inputPassword" class="form-control" placeholder="请填写密码" required name="password">
              <input type="hidden" name="next_url" value="{{ next_url }}">
            <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
          </form>
    
            <div  style="margin-left: 570px">
               <font size="3"> <b>没有注册,点击<a href="/register">注册</a></b></font>
            </div>
        </div>
      </body>
    </html>
    

    三、实现登出功能的代码如下:

    1、编写相关出处理get方法的登出类(在main.py模块中进行)

    class LogoutHandler(BaseHandler):
        @tornado.web.authenticated
        def get(self):
            self.session.delete('username_session')
            next_url = self.get_argument('next', '/')
            self.render('user/login.html', msg="退出成功!!", next_url=next_url)
    

    相关文章

      网友评论

          本文标题:用户登录和登出功能的实现(十五)

          本文链接:https://www.haomeiwen.com/subject/yskupctx.html