Flask SocketIO更新

时间:2019-01-03 17:54:29

标签: jquery flask socket.io flask-socketio

我有一个连接到某些温度传感器的raspi,并且数据以字符串格式发送到pi上的网页。我抓取页面并获取数据,然后尝试使用socketio将其发送到前端的js仪表。我按照有效的基本聊天应用程序上的教程进行操作。我尝试用自己的函数复制该文件,但没有得到任何东西。

app.py

from flask import Flask, render_template
from flask_socketio import SocketIO, send, emit
import bs4 as bs
import ast
import urllib.request

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on('message')
def handle_message(msg):
    print('[server]: ' + msg)
    send(msg, broadcast=True)


@socketio.on('scrape')
def get_data(a0, a1, a2, a3):
    source = urllib.request.urlopen("http://192.168.1.8/data.php")
    soup = bs.BeautifulSoup(source, 'lxml')
    values = ast.literal_eval(soup.p.string)
    values = str(values.get('ainputs'))

    a0 = values[3:8]
    a1 = values[12:18]
    a2 = values[21:27]
    a3 = values[30:36]

    print('[inputs]: ' + a0)
    emit(a0, a1, a2, a3, broadcast=True)


if __name__ == '__main__':
    socketio.run(app)

和index.html(包括脚本)

<html>
<head>

    <title>Chat Room</title>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>

<script type="text/javascript">
    $(document).ready(function() {

        var socket = io.connect('http://127.0.0.1:5000');

        socket.on('connect', function() {
            socket.send("User has connected!");
        });

        socket.on('message', function(msg) {
            $("#messages").append('<li>'+msg+'</li>');
            console.log('data check successful');
        });

        socket.on('scrape', function() {
            socket.emit(a0);
        });

        $('#sendButton').on('click', function() {
            socket.send($('#myMessage').val());
            $('#myMessage').val('');
        });

    });
</script>

<ul id="messages"></ul>
<input type="text" id="myMessage">
<button id="sendButton">Send</button>
</body>
</html>

0 个答案:

没有答案