第一次尝试flask
和socket
两者都令人印象深刻,但我遇到了一个简单的问题。
我的btest模块有list
个数据,可以呈现html table
。此表需要使用以特定间隔出现的新值进行更新。
我正在使用flask socketio
使用新值更新表,但我不知道该怎么做。下面是python代码,我可以渲染初始表。之后我收到500 error
因为套接字无法连接。
如果我禁用刻录渲染,我可以连接并抓取表数据,但不知道如何将其发布到html
( HTML代码)。先感谢您。在我尝试调试时,HTML代码有其他消息。
如果有更简单的方法来执行任务,我会全力以赴。感谢您的支持。
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 :(得分:0)
我建议您查看Flask-SocketIO存储库中的示例代码。该示例显示了页面中的网络延迟,并定期更新它。您可以在示例的那部分之后对您的情况进行建模。
您的代码中存在的主要问题是您正在connect
回调中执行所有操作。但正如您可以在文档中看到的那样,Socket.IO连接仅在connect回调返回True
时建立。由于您永远不会从该功能返回,因此不会建立连接。我上面引用的示例使用后台线程来执行间隔更新,这是一个我认为适合您的更好的模型。