I'm a beginner at flask. I want to implement a function that runs when RAM usage exceeds 80 percent on my server. What is the best way to implement it?
Asked
Active
Viewed 528 times
3 Answers
0
you can import psutil to check the memory.
memory_usage = psutil.virtual_memory().percent
you can check the link to have more ideas about it. https://psutil.readthedocs.io/en/latest/
I wish if my answer is good.

IHA87
- 11
- 4
0
Reading how much ram is used is very simple, as you can also read from this question always asked on stackoverflow:
import psutil
# you can calculate percentage of available memory
print(str(psutil.virtual_memory().available * 100 / psutil.virtual_memory().total))
20.8
To install psutil:
pip install psutil

Matteo Pasini
- 1,787
- 3
- 13
- 26
0
Hey this works psutil
to get the ram usage like this. But if you are calling a different function from a library during the route, if the memory usage spikes it fails to catch. While you can record before and after usage for a process id.
import psutil
def your_route_handler():
process = psutil.Process() #initiate only once
memory_info = process.memory_info()
rss = memory_info.rss
rss_mb = rss / (1024 * 1024)
print(f"Memory usage: {rss_mb} MB")
# Your route logic here...

gamingflexer
- 250
- 3
- 5