2017-01-25 116 views
0

第一次尝试flasksocket都很让人印象深刻,但我坚持一个简单的问题。用烧瓶和烧瓶插座动态更新表格

  1. 我从BTEST模块来的数据的list并且可以呈现html table。这个表格需要用特定时间间隔的新值更新。

  2. 我正在使用flask socketio用新值更新表,但不知道如何去做。下面是python代码,我可以渲染初始表。之后我收到500 error,因为套接字无法连接。

  3. 如果我禁用烧瓶渲染我能够连接并获取表中的数据,但不知道如何发布(以下HTML代码),它html。先谢谢你。我正在尝试调试时,HTML代码还有其他消息。

  4. 如果有更简单的方法来执行这个任务,我全部都是耳朵。谢谢你的支持。

    from flask import Flask, render_template 
    from flask_socketio import SocketIO, emit, send 
    from flask_table import Table, Col 
    import time 
    import btest 
    
    def ntable(): 
        dataz,peername=btest.send(6*1024) 
        NAME,ID,S1,S2,S3,ONLINE,IPConn=btest.status(dataz,peername) 
        data = dict(NAME=[NAME],ID=[ID],S1=[S1],S2=[S2],S3=[S3],ONLINE= [ONLINE],IPConn=[IPConn]) 
    
        class ItemTable(Table): 
         NAME=Col('NAME') 
         ID=Col('ID') 
         S1=Col('S1') 
         S2=Col('S2') 
         S3=Col('S3') 
         ONLINE=Col('ONLINE') 
         IPConn=Col('IPConn') 
        items = [dict(NAME=NAME,ID=ID,S1=S1,S2=S2,S3=S3,ONLINE=ONLINE,IPConn=IPConn)] 
    
    
        table = ItemTable(items) 
        s=(table.__html__()) 
        t=s.replace('<table>','<table class="table table-hover">') 
        return t 
    
        f=open("table.txt",'w') 
        f.write(t) 
        f.close() 
        socketio.emit('message',{'table': t}) 
    
    def ntabrefresh(): 
        dataz,peername=btest.send(6*1024) 
        NAME,ID,S1,S2,S3,ONLINE,IPConn=btest.status(dataz,peername) 
        while S2=="All Downloads Completed.": 
        data = dict(NAME=[NAME],ID=[ID],S1=[S1],S2=[S2],S3=[S3],ONLINE=[ONLINE],IPConn=[IPConn]) 
    
         class ItemTable(Table): 
          NAME=Col('NAME') 
          ID=Col('ID') 
          S1=Col('S1') 
          S2=Col('S2') 
          S3=Col('S3') 
          ONLINE=Col('ONLINE') 
          IPConn=Col('IPConn') 
         items = [dict(NAME=NAME,ID=ID,S1=S1,S2=S2,S3=S3,ONLINE=ONLINE,IPConn=IPConn)] 
    
         table = ItemTable(items) 
         s=(table.__html__()) 
         t=s.replace('<table>','<table class="table table-hover">') 
    
         socketio.emit('message',{'table': t}) 
    
    app = Flask(__name__) 
    app.config['SECRET_KEY'] = 'secret!' 
    socketio = SocketIO(app) 
    
    @app.route('/') 
    def index(): 
        t=ntable() 
        return render_template('mytest0.html',s=t) 
    
    @socketio.on('connect') 
    def test_connect(): 
        print 'client and I are one' 
        socketio.emit('message') 
        time.sleep(3) 
        ntabrefresh() 
    
    if __name__ == '__main__': 
        socketio.run(app) 
    

    <html><head> 
     
         <title>SMPV Status</title> 
     
         <link rel="stylesheet" href="static/css/bootstrap.min.css"> 
     
         <script src="static/jquery.js"></script> 
     
         <script src="static/bootstrap.min.js"></script> 
     
         <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script> 
     
         <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script> 
     
    
     
         <script type="text/javascript" charset="utf-8"> 
     
          $(document).ready(function() { 
     
           // Use a "/test" namespace. 
     
           // An application can open a connection on multiple namespaces, and 
     
           // Socket.IO will multiplex all those connections on a single 
     
           // physical channel. If you don't care about multiple channels, you 
     
           // can set the namespace to an empty string. 
     
           //namespace = '/test'; 
     
           // Connect to the Socket.IO server. 
     
           // The connection URL has the following format: 
     
           //  http[s]://<domain>:<port>[/<namespace>] 
     
           var socket = io.connect('http://' + document.domain + ':' + location.port + '/test'); 
     
           // Event handler for new connections. 
     
           // The callback function is invoked when a connection with the 
     
           // server is established. 
     
           socket.on('connect', function() { 
     
            socket.emit('server said hello'); 
     
            console.log('In connect block sir') 
     
           }); 
     
    
     
           socket.on('message',function(msg){ 
     
            console.log("Recieved table"); 
     
            console.log(msg); 
     
            $('#tbl').append(msg); 
     
    
     
           }); 
     
    
     
           // Event handler for server sent data. 
     
           // The callback function is invoked whenever the server emits data 
     
           // to the client. The data is then displayed in the "Received" 
     
           // section of the page. 
     
           socket.on('my_response', function(msg) { 
     
            $('#log').append('<br>' + $('<div/>').text('Received #' + msg.count + ': ' + msg.data).html()); 
     
           }); 
     
           // Interval function that tests message latency by sending a "ping" 
     
           // message. The server then responds with a "pong" message and the 
     
           // round trip time is measured. 
     
           var ping_pong_times = []; 
     
           var start_time; 
     
           window.setInterval(function() { 
     
            start_time = (new Date).getTime(); 
     
            socket.emit('my_ping'); 
     
           }, 1000); 
     
           // Handler for the "pong" message. When the pong is received, the 
     
           // time from the ping is stored, and the average of the last 30 
     
           // samples is average and displayed. 
     
           socket.on('my_pong', function() { 
     
            var latency = (new Date).getTime() - start_time; 
     
            ping_pong_times.push(latency); 
     
            ping_pong_times = ping_pong_times.slice(-30); // keep last 30 samples 
     
            var sum = 0; 
     
            for (var i = 0; i < ping_pong_times.length; i++) 
     
             sum += ping_pong_times[i]; 
     
            $('#ping-pong').text(Math.round(10 * sum/ping_pong_times.length)/10); 
     
           }); 
     
           // Handlers for the different forms in the page. 
     
           // These accept data from the user and send it to the server in a 
     
           // variety of ways 
     
           $('form#emit').submit(function(event) { 
     
            socket.emit('my_event', {data: $('#emit_data').val()}); 
     
            return false; 
     
           }); 
     
           $('form#broadcast').submit(function(event) { 
     
            socket.emit('my_broadcast_event', {data: $('#broadcast_data').val()}); 
     
            return false; 
     
           }); 
     
           $('form#join').submit(function(event) { 
     
            socket.emit('join', {room: $('#join_room').val()}); 
     
            return false; 
     
           }); 
     
           $('form#leave').submit(function(event) { 
     
            socket.emit('leave', {room: $('#leave_room').val()}); 
     
            return false; 
     
           }); 
     
           $('form#send_room').submit(function(event) { 
     
            socket.emit('my_room_event', {room: $('#room_name').val(), data: $('#room_data').val()}); 
     
            return false; 
     
           }); 
     
           $('form#close').submit(function(event) { 
     
            socket.emit('close_room', {room: $('#close_room').val()}); 
     
            return false; 
     
           }); 
     
           $('form#disconnect').submit(function(event) { 
     
            socket.emit('disconnect_request'); 
     
            return false; 
     
           }); 
     
          }); 
     
         </script> 
     
        </head> 
     
    
     
         <body style="height:1445px"> 
     
    
     
         <meta charset="utf-8"> 
     
         <meta name="viewport" content="width=device-width, initial-scale=1"> 
     
         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
     
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
     
         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
     
    
     
         <div id="tbl"> 
     
          {% block body %} 
     
          {{s|safe}} 
     
          {% endblock %} 
     
    
     
    
     
         </div> 
     
    
     
    
     
        </body></html>

回答

0

我建议你看一下在烧瓶SocketIO库示例代码。该示例显示了网页中的网络延迟,并定期更新它。您可以在示例的该部分之后为您的情况建模。

您的代码中存在的主要问题是您正在执行connect回调中的所有操作。但正如你可以在文档中读到的,只有当连接回调返回True时才建立Socket.IO连接。既然你永远不会从这个函数返回,那么连接就没有了。上面引用的示例使用后台线程来执行间隔更新,这是我认为可以为您工作的更好的模式。

+0

是的,这是超级有用的谢谢你。现在唯一的问题是它是否可以在网络上运行而不是本地主机? –

+0

当然。为什么它不能在公共网络上运行?没有区别。 – Miguel