I'm learning how to use tornado in order to build a simple web app.
However I'm a bit stuck since I can't figure out how to update a template variable with the value that I'm updating in the database
What I have so far:
Tornado code:
import json
import ast
from tornado.ioloop import IOLoop
import tornado.options
from tornado import web, gen
from tornado.httpserver import HTTPServer
from tornado.web import Application
from tornado.websocket import WebSocketHandler
import psycopg2
import psycopg2.extensions
conn = psycopg2.connect('dbname= dname user=user password=pass host=localhost port=5432')
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
class MainHandler(web.RequestHandler):
@gen.coroutine
def get(self):
self.render('index.html', result='test')
def poll(fd ,ev):
state = conn.poll()
if state == psycopg2.extensions.POLL_OK:
if conn.notifies:
notify = conn.notifies.pop(0)
dict_notify = json.loads(notify.payload)
print(dict_notify['new_value']['value'])
def listen(channel):
cursor = conn.cursor()
cursor.execute('LISTEN test_channel;')
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers = [(r'/', MainHandler)], debug = True)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen('8888')
io_loop = IOLoop.instance()
io_loop.add_handler(conn.fileno(), poll, io_loop.READ)
listen()
io_loop.start()
My template looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Index</title>
</head>
<body>
<div>{{ result }}</div>
</body>
</html>
Now, what I want is that the value i get from pool() to go as {{result}} in my template. The pool() function always prints the value I update in the database (postgresql db) however I can't figure out how to get it in the template. Any ideas?
Tornado's RequestHandler
handles asynchronous HTTP requests, i.e. it can't update the response until the next request is made. For that you need to query the database from its methods and then pass the result to self.render
, which inserts it into the template before sending it back.
In order to push the real-time changes from the database you need to use the WebSocketHandler
(which you import but use nowhere in the given code), and then you also need some client-side code (e.g. Javascript) to accept the pushed data and insert it into the rendered page.