tornado 簡單使用實例

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options
import os.pathhtml

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)web

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

class LoginHandler(BaseHandler):
    def get(self):
        self.render('login.html')app

    def post(self):
        self.set_secure_cookie("username", self.get_argument("username"))
        self.redirect("/")tornado

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

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

if __name__ == "__main__":
    tornado.options.parse_command_line()url

    settings = {
        "template_path": os.path.join(os.path.dirname(__file__), "templates"),
        "cookie_secret": "bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=",
        "xsrf_cookies": True,
        "login_url": "/login"
    }orm

    application = tornado.web.Application([
        (r'/', WelcomeHandler),
        (r'/login', LoginHandler),
        (r'/logout', LogoutHandler)
    ], **settings)server

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
模板文件在應用templates/目錄下。

 登陸表單:login.html
<html>
    <head>
        <title>Please Log In</title>
    </head>

    <body>         <form action="/login" method="POST">             {% raw xsrf_form_html() %}             Username: <input type="text" name="username" />             <input type="submit" value="Log In" />         </form>     </body> </html>  歡迎回客:index.html <html>     <head>         <title>Welcome Back!</title>     </head>     <body>         <h1>Welcome back, {{ user }}</h1>     </body> </html>

相關文章
相關標籤/搜索