即使在提交表单后也显示相同的页面

Display the same page even after form submission

在下面的简单表单提交中,我输入了一个名称,它在提交表单后打印了一条消息 ("BY which i mean the form is gone and only message is being displayed "),但我想在表单

中显示相同的消息
enter code here
import tornado.ioloop
import tornado.web

class Main(tornado.web.RequestHandler):
    def get(self):
            self.render("auth.html")
    def post(self):
            ab=self.get_body_argument("username","")
            self.write(ab+" printing in a new page")


application = tornado.web.Application([
    (r"/", Main),
    ],debug=True,)

if __name__ == "__main__":
application.listen(8054)
tornado.ioloop.IOLoop.instance().start()

为了方便起见,这里是 HTML 页面:

<html>

<head>
Welcome
</head>
<body>
    <div id="complete">

        <div id="form">
            <form action="/" method="post">
                <input type= "text" name="username" >
                <input type="submit" value="Login">
            </form>
        </div>
    </div>
</body>
</html>

您有两个单独的处理程序用于 POST 和 GET,但只有在 GET 中您才真正呈现表单。接下来,将 writerender 一起使用不是一个好主意 - 它会起作用,但文本将在 HTML 之外(之前或之后),解决方案 - 模板变量。

import tornado.ioloop
import tornado.web

class Main(tornado.web.RequestHandler):
    def get(self):
        self.render("auth.html", message=None)

    def post(self):
        msg = "{} printing in a new page".format(
            self.get_body_argument("username","")
        )
        self.render("auth.html", message=msg)


application = tornado.web.Application([
    (r"/", Main),
    ],debug=True,)

if __name__ == "__main__":
    application.listen(8054)
    tornado.ioloop.IOLoop.instance().start()

和auth.py

<html>

<head>
Welcome
</head>
<body>
    <div id="complete">

        <div id="form">
            {% if message is not None %}
            <p>{{ message }}</p>
            {% end %}
            <form action="/" method="post">
                <input type= "text" name="username" >
                <input type="submit" value="Login">
            </form>
        </div>
    </div>
</body>
</html>

有关龙卷风模板的更多信息:http://tornadokevinlee.readthedocs.org/en/latest/template.html