Backend Development 6 min read

Building a Real-Time Linux Resource Monitoring Dashboard with Flask, MongoDB, and Vue

This tutorial demonstrates how to create a real-time Linux system resource monitoring web page using Flask for backend APIs, MongoDB for data storage, and Vue.js for a dynamic frontend that updates every 30 seconds.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Building a Real-Time Linux Resource Monitoring Dashboard with Flask, MongoDB, and Vue

This tutorial demonstrates how to create a real-time Linux system resource monitoring web page using Flask for backend APIs, MongoDB for data storage, and Vue.js for a dynamic frontend that updates every 30 seconds.

First, ensure you have installed Flask, PyMongo, Vue, axios, psutil, vnstat, pymysql, and redis dependencies.

In the Python Flask application, create a new API route to retrieve system resource details. Use psutil for CPU, memory, disk, and system load; pymysql for MySQL slow queries; redis for Redis info; and vnstat for network bandwidth.

from flask import Flask, jsonify
from flask_restful import Resource, Api
import psutil
import vnstat
import pymysql
import redis
import os
import datetime

app = Flask(__name__)
api = Api(app)

class SystemResource(Resource):
    def get(self):
        cpu_percent = psutil.cpu_percent(interval=1)
        memory_info = psutil.virtual_memory()
        disk_usage = psutil.disk_usage("/")
        mysql_slow_queries = self.get_mysql_slow_queries()
        redis_info = self.get_redis_info()
        network_info = self.get_network_info()
        system_load = os.getloadavg()
        return jsonify({
            "cpu": cpu_percent,
            "memory": memory_info.percent,
            "disk": disk_usage.percent,
            "mysql": mysql_slow_queries,
            "redis": redis_info,
            "network": network_info,
            "system_load": system_load
        })

    def get_mysql_slow_queries(self):
        conn = pymysql.connect(host="localhost", user="username", password="password", db="db")
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM slow_query_log")
            result = cursor.fetchall()
        return result

    def get_redis_info(self):
        r = redis.Redis(host="localhost", port=6379, db=0)
        info = r.info()
        return info

    def get_network_info(self):
        stats = vnstat.read_totals("/path/to/vnstat.db")
        total_bytes_sent = stats[0]["TX"]
        total_bytes_received = stats[0]["RX"]
        current_date_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        return {
            "total_bytes_sent": total_bytes_sent,
            "total_bytes_received": total_bytes_received,
            "current_date_time": current_date_time
        }

api.add_resource(SystemResource, "/system")

if __name__ == "__main__":
    app.run(debug=True)

This Flask code defines a SystemResource endpoint at /system that returns JSON with CPU, memory, disk usage, MySQL slow queries, Redis info, network statistics, and system load.

On the frontend, create a Vue component that displays the data in a table. Use axios to fetch data from the /system API and update the table.

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>Resource Type</th>
          <th>Usage Percentage</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(resource, index) in resources" :key="index">
          <td>{{ resource.type }}</td>
          <td>{{ resource.percentage }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: "SystemMonitor",
  data() {
    return {
      resources: []
    };
  },
  mounted() {
    this.getResources();
    setInterval(() => {
      this.getResources();
    }, 30000);
  },
  methods: {
    getResources() {
      axios.get("/system")
        .then(response => {
          this.resources = response.data;
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
};
</script>

The Vue component renders a table where each row shows a resource type and its usage percentage. The mounted lifecycle hook calls getResources initially and then every 30 seconds via setInterval to keep the data up to date.

By combining these backend and frontend pieces, you have a functional dashboard that monitors Linux server resources in real time and refreshes every half minute.

Vue.jsREST APIFlaskMongoDBReal-time Dashboardlinux monitoring
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.