温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python Linux下构建实时数据监控平台

发布时间:2024-09-12 12:00:41 来源:亿速云 阅读:79 作者:小樊 栏目:编程语言

在Linux下构建实时数据监控平台,你可以使用Python的一些库和工具

  1. 安装必要的库:
pip install flask flask-socketio eventlet requests
  1. 创建一个名为monitor.py的文件,然后编写以下代码:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import eventlet
import requests
import json

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

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

@socketio.on('connect')
def handle_connect():
    print('Client connected')

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

def fetch_data():
    while True:
        try:
            response = requests.get('https://api.example.com/data')
            data = response.json()
            socketio.emit('new_data', data)
        except Exception as e:
            print(f"Error fetching data: {e}")
        eventlet.sleep(5)

if __name__ == '__main__':
    eventlet.spawn(fetch_data)
    socketio.run(app, host='0.0.0.0', port=8000)
  1. 创建一个名为templates的文件夹,并在其中创建一个名为index.html的文件。将以下代码添加到该文件中:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
   <title>Real-time Data Monitor</title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js"></script>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Real-time Data Monitor</h1>
    <div id="data"></div>

   <script>
        $(document).ready(function() {
            var socket = io.connect('http://' + document.domain + ':' + location.port);
            socket.on('connect', function() {
                console.log('Connected to server');
            });

            socket.on('new_data', function(data) {
                $('#data').html(JSON.stringify(data, null, 2));
            });
        });
    </script>
</body>
</html>
  1. 运行监控平台:
python monitor.py

现在,你可以在浏览器中访问http://localhost:8000,查看实时数据。请注意,你需要将https://api.example.com/data替换为你自己的数据源API。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI