简体   繁体   中英

How to call a javascript function from tornado web <python>?

I want to make a live chart with smoothy js. My server is running from tornado, this is written in python. Smoothy can refresh the chart live. In python I render the html file, which includes the smoothy, but I don't know how to refresh data from python (because my datas in SQL database) There is the function called from html file: (call it ex.html)

  var line1 = new TimeSeries();
  var line2 = new TimeSeries();
  var i = 1;
  setInterval(function() {
    line1.append(new Date().getTime(), Math.random);
    line2.append(new Date().getTime(), Math.random());
  }, 1000);

As you see the append method updates my chart, and the second parameter is the value(x axis). So my question is: How to add information from tornado web using smoothie?

And there is my python code:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("ex.html")

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

If my description isn't understandable, please drop me a message. Thanks for the answer!

You can pass the information to you template, for example

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        data = {"x": "01/01/17", "y": 100}
        self.render("ex.html", data=data)

and in the html template

line1.append({{ data["x"] }},{{ data["y"] }} )

This is just a simple example, check the template documentation for more complex examples, like using loops.

This way is a static, ok for the ajax here is a example.

<script type="text/javascript">
        setInterval(function() {
        $.getJSON("/stats",function(data){
        line1.append(data.time, data.in);
        line2.append(data.time, data.in);
        });
        }, 1000);
</script>
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("ex.html")

class Stats(tornado.web.RequestHandler):
    def get(self):
        self.write({"time":"time","in":10})

def make_app():
    return tornado.web.Application([
        (r"/stats", Stats),
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM