2017-12-26 11 views
0

mongoDBからプルするWebページを作成しようとしていて、返された値に基づいてテーブルを更新しています。現在、私はmongoDBにモータを使って問い合わせを行い、各メッセージを非同期に処理することができます。しかし、私はページの読み込みごとに1回だけ書くことができます。私はページが開いている限り、mongoDBから引き続き竜巻を設定する方法があるかどうか疑問に思っていますか?これは、私は現在、ページの負荷ごとに動作していますが、mongoDBが更新されたときに動的に更新する方法を確信できません。非同期mongoDBクエリに基づいてテーブルを継続的に更新する

import tornado.ioloop, tornado.web, motor 

class LoadHandler(tornado.web.RequestHandler): 
    @tornado.web.asynchronous 
    def get(self): 
     db = self.settings['db'] 
     self.write(''' 
     <<!doctype html> 
     <html lang="en"> 
      <head> 
       <title>Coin Info</title> 
       <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
       <script type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
       <style> 
        div.table {border: 1px solid black; display: table; width: 500px;} 
        div.row {border: 1px solid black; display: table-row; } 
        div.cell {border: 1px solid black; display: table-cell; } 
        div.wrapper { float: left;width: 200px; } 
       </style> 
      </head> 
      <body> 
       <div class="wrapper"> 
        <div class="table"> 
         <div class="header"> 
          <div class="cell">Name</div> 
          <div class="cell">Item1</div> 
          <div class="cell">Item2</div> 
          <div class="cell">Item3</div> 
         </div> 
     ''') 
       db.posts.find().sort([('_id',-1)]).each(self._got_message) 

    def _got_message(self, message,error): 
     if error: 
      raise tornado.web.HTTPError(500, error) 
     elif message: 
      self.write('<div class="row">') 
      self.write('<div class="cell" data-name={0}>{0}</div>'.format(message['values']['name'])) 
      self.write('<div class="cell" data-item1={0}>{0}</div>'.format(message['item1'])) 
      self.write('<div class="cell" data-item2={0}>{0}</div>'.format(message['values']['item2'])) 
      self.write('<div class="cell" data-item3={0}>{0}</div>'.format(message['values']['item3'])) 
      self.write('</div>') 
     else: 
      self.write('</div></div></div></div></body>') 
      self.finish() 

class MainHandler(tornado.web.RequestHandler): 
    @tornado.web.asynchronous 
    def get(self): 
     self.write('here') 
     self.finish() 

db = motor.MotorClient().current_db 

application = tornado.web.Application([ 
     (r'/load/', LoadHandler), 
     (r'/', MainHandler) 
    ], db=db 
) 

print('Listening on http://localhost:5000') 
application.listen(5000) 
tornado.ioloop.IOLoop.instance().start() 

答えて

1

通常のHTTP接続は、サーバーが応答の送信を終了するとすぐに閉じられます。したがって、接続が閉じられた後にクライアントにデータを送信することはできません。

クライアントにリアルタイムのデータ更新を送信するには、Websocketを使用できます。通常のHTTP接続とは異なり、Websocket接続は必要なだけ開いたままで、サーバーはいつでもクライアントにデータを送信できます。

竜巻のdocumentationは、Websocketを使い始めるのに大変便利です。先進的なものには、demoのチャットアプリがあります。自由に遊べます。

関連する問題