Flask 我是不是太慢了,还是我错过了什么?

Flask 我是不是太慢了,还是我错过了什么?,flask,flask-socketio,Flask,Flask Socketio,全部 我正在开发一个应用程序,它从温度传感器接收数据,并在localhost:5000的烧瓶服务网页中动态打印数据 为了从温度传感器接收数据,使用udp服务器。receive函数在线程内实现。为了“实时”将数据打印到网页上,socketio被采用——它都在“app.py”中运行 我面临的问题是在网页上打印数据的速度太慢。为了测试我的代码,我开发了一个udp客户端(client.py),它连接到我的app.py,并通过用户输入发送数据。我观察到的是,套接字接收数据(我可以打印我在client.py

全部

我正在开发一个应用程序,它从温度传感器接收数据,并在localhost:5000的烧瓶服务网页中动态打印数据

为了从温度传感器接收数据,使用udp服务器。receive函数在线程内实现。为了“实时”将数据打印到网页上,socketio被采用——它都在“app.py”中运行

我面临的问题是在网页上打印数据的速度太慢。为了测试我的代码,我开发了一个udp客户端(client.py),它连接到我的app.py,并通过用户输入发送数据。我观察到的是,套接字接收数据(我可以打印我在client.py中发送的所有内容以及我在app.py中接收的所有内容),但我的socketio emit函数和网站反馈之间的某些东西会使更新过程变慢

我错过什么了吗?你们能帮我找出为什么我的代码中这个过程这么慢吗

非常感谢您的帮助!!非常感谢

app.py

from flask import Flask, render_template, flash, url_for, redirect, request
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO, emit
import socket
import threading

HOST = ''
PORT = 3456
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
orig = (HOST, PORT)
udp.bind(orig)

app = Flask(__name__)
app.config ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///measurements.sqlite3'
app.config ['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = "secret!"

async_mode = None
socketio = SocketIO(app, async_mode=async_mode)

def thread_function():
    last_temp = 0

    while True:
        temperatura, client = udp.recvfrom(5)
        temp = float(temperatura)
        print("Temp: " + str(temp))
        print("Last temp: " + str(last_temp))

        if (temp != last_temp):
            socketio.emit('my_response', {'temp': temp})
            print("I am here!")
            last_temp = temp

    udp.close()


receive_thread = threading.Thread(target=thread_function)
receive_thread.start()

@app.route('/')
def home():
    # Home acts as a dashboard for the page
    return render_template('index.html')

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

import socket

HOST = '127.0.0.1'  
PORT = 3456            
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dest = (HOST, PORT)

print('Para sair use CTRL+X\n')

msg = input()

while msg != '\n':
    udp.sendto(bytes(msg, "utf-8"), dest)
    msg = input()

udp.close()
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Temperature sense</title>
    <style>
    img {
      display: block;
      margin-left: auto;
      margin-right: auto;
    }
    button {
      background-color: #4180a0;
      border: none;
      border-radius: 8px;
      color: white;
      <!--- padding: 32px 64px; --->
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      <!--- margin: 4px 2px; --->
      cursor: pointer;
      width: 128px;
      height: 64px;
    }
    button.button:hover{
        background-color: #2a2349;
    }
    div {
        border: 1px;
        border-style: solid;
        border-color: #bebbb2;
        padding: 8px;
    }
    measurementPrint{
        border: 1px;
        border-style: solid;
        border-color: #bebbb2;
        padding: 8px;
    }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            // Connect to the Socket.IO server.
            // The connection URL has the following format, relative to the current page:
            //     http[s]://<domain>:<port>[/<namespace>]
            var socket = io();

            // 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').text(msg.temp);
            });

        });
    </script>
</head>

<body>
    <div>

        <img src="/static/images/mentorphotonics.jpeg" class="center" alt="Mentor Photonics"  width="200" height=auto />

        <p>
            <a href=/ ><button class=button >Realtime</button></a>
                <measurementPrint>
                    <b>Temperature: <span id="log"></span></b>
                </measurementPrint>
        </p>
        <p><a href=export ><button class=button >Export</button></a></p>
        <p><a href=about ><button class=button >About</button></a></p>
    </div>
</body>

</html>

温度感
img{
显示:块;
左边距:自动;
右边距:自动;
}
钮扣{
背景色:#4180a0;
边界:无;
边界半径:8px;
颜色:白色;
文本对齐:居中;
文字装饰:无;
显示:内联块;
字体大小:16px;
光标:指针;
宽度:128px;
高度:64px;
}
按钮。按钮:悬停{
背景色:#2a2349;
}
div{
边界:1px;
边框样式:实心;
边框颜色:#bebbb2;
填充:8px;
}
测量点{
边界:1px;
边框样式:实心;
边框颜色:#bebbb2;
填充:8px;
}
$(文档).ready(函数(){
//连接到Socket.IO服务器。
//相对于当前页面,连接URL具有以下格式:
//http[s]:/:[/]
var socket=io();
//服务器发送数据的事件处理程序。
//只要服务器发出数据,就会调用回调函数
//发送到客户端。然后,数据显示在“已接收”中
//本页的第节。
socket.on('my_response',函数(msg){
$('#log').text(msg.temp);
});
});

温度:

伙计们

我重新研究了Miguel Grinberg的教程中的示例,并调整了代码。 主要问题是:

  • 我没有使用“thread=socketio.start\u background\u task(background\u thread)”结构,就像他在@socketio.event中使用的那样
  • UDP的recvfrom被阻塞。为了解决这个问题,我设置了一个超时“udp.settimeout(0.1)”,使其成为非阻塞的。但是,现在您应该使用try;发生超时时的异常对
  • 你好,法维罗