Home  >  Article  >  Backend Development  >  Example code for python tornado websocket real-time log display

Example code for python tornado websocket real-time log display

高洛峰
高洛峰Original
2017-03-21 13:41:491989browse

1. Topic: Real-time display of log files dynamically generated by the server

2. Process:

 1. Client browser Establish a websocket link with the server, the server hangs up to save the link instance, and waits for new content to trigger the return action

 2. Log server scriptLoop to discover new content, find new lines and wait for tornadoAPI POST sends new content

 3. The tornado processor receives the new content and returns the new line to the saved client link through websocket

 4. The client browser receives the New content, modification, display

3.Code:

1. tornado server urlrouting, basic page handler and html:

    #模块路径根据自身项目而定
    (r'/logs/index/',               'apps.logs.handler.IndexHandler'),
    (r'/logs/newlinesforcallbacker/',       'apps.logs.handler.WriteNewLinesHandler'),
    (r'/logs/newlinesforserver/',           'apps.logs.handler.ReceiveNewLinesHandler'),
class IndexHandler(BaseHandler):
    ''' 主页 '''
    def get(self, *args, **kwargs):
        self.render('logs/index.html')
<div align="center">
    <h2>this logs monitor</h2>
    <div style="width: 70%" id="main">
    <!-- 行展示 -->
    </div>
</div>

2. Server-side websocket handler (WriteNewLinesHandler), save and delete link processing class and client-side websocket request js

class ProStatus(object):
    &#39;&#39;&#39; 处理类 &#39;&#39;&#39;

    w_register = []

    def register(self, callbacker):
        &#39;&#39;&#39; 记录客户端连接实例 &#39;&#39;&#39;
        self.w_register.append(callbacker)

    def unregister(self, callbacker):
        &#39;&#39;&#39; 删除客户端连接实例 &#39;&#39;&#39;
        self.w_register.remove(callbacker)

    def makelines(self, lines):
        &#39;&#39;&#39; 处理接受的行内容 &#39;&#39;&#39;
        pass

    def trigger(self, line):
        &#39;&#39;&#39; 向所有被记录客户端发送最新内容 &#39;&#39;&#39;
       pass

class WriteNewLinesHandler(tornado.websocket.WebSocketHandler):
    &#39;&#39;&#39; 接受websocket链接,保存链接实例 &#39;&#39;&#39;
    def check_origin(self, origin):     #针对websocket处理类重写同源检查的方法
        return True

    def open(self):
        &#39;&#39;&#39; 处理新的连接  &#39;&#39;&#39;
        ProStatus().register(self)

    def on_close(self):
        ProStatus().unregister(self)  #删除客户端连接

    def on_message(self, message):
        pass
$(function(){
            function requestText(){
                host = "ws://" + location.hostname + ":" + location.port + "/logs/newlinesforcallbacker/"
                websocket = new WebSocket(host)

                websocket.onopen = function(evt){}      // 建立连接
                websocket.onmessage = function(evt){    // 获取服务器返回的信息
                    data = $.parseJSON(evt.data)
                    $("#main").append(data+"</br>")     //写入页面
                }
                websocket.onerror = function(evt){}
            }

            requestText()
})

3. tornado waits for the script to submit new content processing handler(ReceiveNewLinesHandler), sending new content to the suspended clientFunction and traversing the log to submit new content script

class ProStatus(object):
    &#39;&#39;&#39; 处理类 &#39;&#39;&#39;

    w_register = []

    def register(self, callbacker):
        &#39;&#39;&#39; 记录客户端连接实例 &#39;&#39;&#39;
        pass

    def unregister(self, callbacker):
        &#39;&#39;&#39; 删除客户端连接实例 &#39;&#39;&#39;
        pass

    def makelines(self, lines):
        &#39;&#39;&#39; 处理接受的行内容 &#39;&#39;&#39;
        for line in lines:
            self.trigger(line)

    def trigger(self, line):
        &#39;&#39;&#39; 向所有被记录客户端发送最新内容 &#39;&#39;&#39;
        for callabler in self.w_register:
            callabler.write_message(json.dumps(line))

class ReceiveNewLinesHandler(BaseHandler):
    &#39;&#39;&#39; 接受服务器端脚本提交的最新行内容 &#39;&#39;&#39;
    def post(self, *args, **kwargs):
        linesdata = self.get_argument(&#39;lines&#39;, &#39;&#39;)
        #print type(json.loads(linesdata))
        ProStatus().makelines(json.loads(linesdata))
#-*-coding:utf-8-*-
author = &#39;zhouwang&#39;
import time
import urllib
import urllib2
import json

p = 0
while True:
    f = open(&#39;logs.txt&#39;, &#39;r+&#39;)
    f.seek(p, 0)    #偏移到上次结束位置

    lines = f.readlines()

    if lines:
        #对行内容操作, 向服务器发送最新行内容
        data = urllib.urlencode({&#39;lines&#39;:json.dumps(lines)})
        url = &#39;http://localhost:8800/logs/newlinesforserver/&#39;
        req = urllib2.Request(url, data)
        res_data = urllib2.urlopen(req)
        #print res_data.read()

    #获取当前位置,作为偏移值
    p = f.tell()
    f.close()
    time.sleep(1)

The above is the detailed content of Example code for python tornado websocket real-time log display. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn