首页 > 代码库 > tornado用户验证

tornado用户验证

1.重写get_current_user()方法

class BaseHandler(tornado.web.RequestHandler):    def get_current_user(self):        return self.get_secure_cookie("username")

获取cookie中用户信息

2.登录url

class LoginHandler(BaseHandler):    def get(self):        self.render(login.html)    def post(self):        self.set_secure_cookie("username", self.get_argument("username"))        self.redirect("/")

代码是简单的示例,没有做登录验证

3.主界面url

class WelcomeHandler(BaseHandler):    @tornado.web.authenticated    def get(self):        self.render(index.html, user=self.current_user)

@tornado.web.authenticated装饰器包裹get方法时,表示这个方法只有在用户合法时才会调用,authenticated装饰器会调用get_current_user()方法获取current_user的值,若值为False,则重定向到登录url

4.退出登录url

class LogoutHandler(BaseHandler):    def get(self):        if (self.get_argument("logout", None)):            self.clear_cookie("username")            self.redirect("/")

删除cookie中的用户,重定向到登录url

5.服务器设置

if __name__ == "__main__":    tornado.options.parse_command_line()    settings = {        "template_path": os.path.join(os.path.dirname(__file__), "templates"),        "cookie_secret": "bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=",        "xsrf_cookies": True,        "login_url": "/login"    }    application = tornado.web.Application([        (r/, WelcomeHandler),        (r/login, LoginHandler),        (r/logout, LogoutHandler)    ], **settings)    http_server = tornado.httpserver.HTTPServer(application)    http_server.listen(options.port)    tornado.ioloop.IOLoop.instance().start()

login_url参数设定了登录url

tornado用户验证