I write a simple Flask app to test its memory usage.
Here is the code.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
with open("file.txt", "r") as fd:
text = fd.read()
return "Hello World!"
if __name__ == "__main__":
app.run(host="0.0.0.0")
file.txt is created by this command and its size is 50MB.
base64 /dev/urandom | head -c 50000000 > file.txt
Run it with this command:
python3 test.app
If running without reading file.txt, the memory usage is 18448KB.
If running and reading file.txt, the memory usage is 18988KB.
This file is 50MB, but the memory usage only increases 540KB. I don't understand how Python works.
Because the memory is garbage collected after the view exits. For the short time that the view is running, you will indeed be using 50MB extra memory.
This has nothing to do with Flask, the same thing would happen with a regular Python function that reads such a file then discards it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With