python使用tornado实现登录和登出
本文实例为大家分享了tornado实现登录和登出的具体代码,供大家参考,具体内容如下
main.py如下:
import tornado.httpserver import tornado.ioloop import tornado.web import tornado.options import os.path from tornado.options import define, options define("port", default=8000, help="run on the given port", type=int) class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): return self.get_secure_cookie("username") class LoginHandler(BaseHandler): def get(self): self.render('login.html') def post(self): self.set_secure_cookie("username", self.get_argument("username")) self.redirect("/") class WelcomeHandler(BaseHandler): @tornado.web.authenticated def get(self): self.render('index.html', user=self.current_user) class LogoutHandler(BaseHandler): def post(self): if (self.get_argument("logout", None)): self.clear_cookie("username") self.redirect("/") if __name__ == "__main__": tornado.options.parse_command_line() settings = { "template_path": os.path.join(os.path.dirname(__file__), "templates"), "cookie_secret": "bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=", "login_url": "/login" } application = tornado.web.Application([ (r'/', WelcomeHandler), (r'/login', LoginHandler), (r'/logout', LogoutHandler) ],debug= True,**settings) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
index.html
<html> <head> </head> <body> <p>Hello {{ user }}</p> <form action="/logout?logout=1" method="post"> <input type="submit" value="Log out"></br> </body> </html>
login.html
<html> <head> </head> <body> <h>Login Page</h> <form action="/login" method="post">Name:<input type="text" name="username"></br> <input type="submit" value="Sign in"></br> </form> </body> </html>
相关推荐
selectY 2020-07-18
zhangxuelong 2020-06-14
zhangxuelong 2020-06-14
牧码人 2020-06-14
hjhmpl 2020-06-14
thundor 2020-05-05
Cagey 2020-04-25
KarlDoenitz 2020-04-16
牧码人 2020-01-25
KarlDoenitz 2019-12-28
hjhmpl 2019-12-25
hjhmpl 2019-12-17
selectY 2019-12-11
KarlDoenitz 2019-12-06
selectY 2019-12-05
Cagey 2019-12-05
hjhmpl 2019-11-03
牧码人 2019-11-03
chenzhanhai 2019-04-09