Search code examples
httprefreshtornado

How to refresh the client in Tornado?


After the client press a button(method = "post"),I would do something in the database,then refresh the client's current page.How can I do this?


Solution

  • Project tree:

    $ tree
    .
    ├── static
    │   └── scripts
    │       └── test.js
    ├── templates
    │   └── index.html
    └── test.py
    

    Tornado code:

    # test.py
    import os
    import logging
    import time
    
    import tornado.httpserver
    import tornado.ioloop
    import tornado.options
    import tornado.web
    import tornado.gen
    
    from tornado.options import define, options
    define("port", default=8888, help="run on the given port", type=int)
    
    class IndexHandler(tornado.web.RequestHandler):
        def initialize(self, data):
            self.data = data
        def get(self):
            self.render("index.html", data=self.data["status"])
        @tornado.web.asynchronous
        @tornado.gen.engine
        def post(self):
            action = self.get_argument('action')
            if action == 'reload':
                logging.info('background job start')
                yield tornado.gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, time.time() + 3)
                logging.info('background job stop')
                self.data["status"] = "reloaded"
                self.finish("{}")
    
    class Application(tornado.web.Application):
        def __init__(self):
            self.data = {"status":"initialized"}
            handlers = [
                (r"/", IndexHandler, {"data":self.data}),
            ]
            settings = dict(
                static_path = 'static',
                template_path=os.path.join(os.path.dirname(__file__), "templates"),
            )
            tornado.web.Application.__init__(self, handlers, **settings)
    
    if __name__ == "__main__":
        tornado.options.parse_command_line()
        app = Application()
        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(options.port)
        tornado.ioloop.IOLoop.instance().start()
    

    Template page:

    <!-- index.html -->
    <html>
    <head>
        <title>JavaScript reload example</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
        <script src="{{ static_url('scripts/test.js') }}" type="application/javascript"></script>
    </head>
    <body>
        <input type="submit" value="reload" id="reload-button" /><br/>
        {{data}}
    </body>
    </html>
    

    JavaScript file:

    /* test.js */
    $(document).ready(function() {
        $('#reload-button').click(function(event) {
            jQuery.ajax({
                url: '//localhost:8888/',
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'reload',
                },          
                success: function() {
                    window.location.reload(true);
                }
            });
        });
    });
    

    I'm yielding add_timeout to simulate database operation.