Are you tired of manually checking your Raspberry Pi’s disk space and latest files? With a few lines of Python code and the Flask web framework, you can create a simple application that monitors your Raspberry Pi for you.
In this post, we will walk through the code that monitors the free disk space on your Raspberry Pi and returns the latest modified file in a specified folder.
To get started, we need to install the Flask and psutil libraries.
Once you have the dependencies installed, create a new Python file and copy the following code:
from flask import Flask import os import psutil app = Flask(__name__) @app.route("/disk-space") def disk_space(): disk = psutil.disk_usage("/") free = disk.free // (1024 * 1024) return str(free) + " MB" @app.route("/file") def get_recent_file(): folder = "/home/pi/Documents" files = os.listdir(folder) files.sort(key=lambda x: os.path.getmtime(os.path.join(folder, x))) recent_file = files[-1] return recent_file if __name__ == '__main__': app.run(port=8989)
Let’s break down this code.
First, we import the Flask, os, and psutil libraries. Flask is the web framework that we will use to create the application. The os library provides a way to interact with the Raspberry Pi’s file system. Psutil is a cross-platform library for retrieving system information.
Next, we create a new Flask application instance and define two routes: /disk-space and /file.
The /disk-space route uses the psutil library to obtain the amount of free disk space on the Raspberry Pi’s root file system (“/”). The value is converted to megabytes and returned as a string.
The /file route lists all files in the specified folder (in this case, the “Documents” folder in the Raspberry Pi user’s home directory) and returns the name of the most recently modified file. The files are sorted based on their modification time using os.path.getmtime.
Finally, we start the Flask application on port 8989.
To run this application on your Raspberry Pi, save the code to a file (e.g. app.py) and run the following command:
This will start the Flask application, and you can access the routes by visiting http://:8989/disk-space and http://:8989/file in your web browser.
That’s it! With just a few lines of code, you can now monitor your Raspberry Pi’s free disk space and latest files.
You can easily modify this code to add more routes and functionality to suit your needs. Happy coding!