使用 Dajax 流式传输日志消息

Use Dajax to stream log messages

我正在尝试为我的网站创建一个记录器 window,将 python 记录器消息流式传输到 javascript 弹出窗口 window。我已经到了这样的地步,如果我关闭 window 并重新打开它,将显示新消息,但我想写一些 javascript 自动刷新 window (并调用 dajaxice ) 每 N 秒。

我的ajax.py:

@dajaxice_register(method='GET')
def getLogs(request):
  fname = "/path/to/LOG_2015-07-08.log"
  with open(fname,"r") as f:
    lines = f.readlines()
  lines = lines[-15:]  //
  logger.info("Displaying Logs")
  return json.dumps({'message':lines})

我的html:

<script language="javascript" type="text/javascript">
  function popitup(data) {
    sessionStorage.setItem("logs",data.message);
    newWindow = window.open('/InterfaceApp/LogViewer', 'Log Viewer', 'height=400,width=800,status=yes');
    if(newWindow && !newWindow.closed){

    newWindow.location.reload(true);  //this is my first attempt at a refresh, wasn't quite what I wanted.

    newWindow.focus();
    } 
  }
</script>
<div class="container">
  <input id="LogMessages" type="button" value="View Log Messages" onclick="Dajaxice.InterfaceApp.getLogs(popitup)"/>
</div>

重申一下,我想单击按钮并弹出一个 window。我希望弹出窗口 window 每 N 秒刷新一次日志文件的最后 15 行(每次用户浏览网站时这些行都会添加到日志中)。 ajax.py 中的 dajaxice 函数是获取日志文件的功能,因此需要以某种方式调用以某种方式包含在刷新中。

谁能帮我解决这个问题?我已经为此苦苦挣扎了好几天。

谢谢!!

我能够自己弄明白。下面的代码对我有用。

ajax.py:

@dajaxice_register(method='GET')
def getLogs(request):
  fname = "/path/to/LOG_2015-07-09.log"
  with open(fname,"r") as f:
    lines = f.readlines()
  lines = lines[-15:]
  return json.dumps({'message':lines})

html:

 <div class="container-fluid">
  <h4 class="text-center">Log Messages</h4>
  <div class="content">
    <span class='value'></span>
  </div>
  <script language="javascript" type="text/javascript">
    function saveLogs(data){
      sessionStorage.setItem("logs",data.message);
    }
      $(document).ready(
        function() {
          setInterval(function() {
            Dajaxice.InterfaceApp.getLogs(saveLogs);
            var logs = sessionStorage.getItem("logs");
            document.querySelector('.content .value').innerText = logs;      
          }, 3000);
        });
  </script>
</div>        

我使用了 dajaxice 而不是直接 ajax,在正确配置所有设置之前,它花了很多时间摆弄,但它似乎比尝试学习如何更容易将 ajax 和 php 集成到我的 django 项目中。