There is a package that can audit Python memory leaks just by inserting a decorator. ‘Python Memory Leak Inspection’ is sufficient with the package insertion.
pip install memory_profiler
I tried adding it to each method of FastAPI, but the results were not organized.
It’s not easy to distinguish unit operations on the complexity and continuity of the API pipe in server programs.
I created test cases, ran individual functions, and tested them by calling them repeatedly.
from memory_profiler import profile
class Test:
@profile
def detect_price_search(self):
with get_engine().connect() as conn:
...
try:
return CustomJSONResponse(content=contents)
except ValueError as e:
# Handle the error or modify the data as needed
return CustomJSONResponse(content={'error': 'Serialization error'}, status_code=500)
if __name__ == '__main__':
data = Test().detect_price_stk_code()
data = Test().detect_price_stk_code()
data = Test().detect_price_stk_code()
data = Test().detect_price_stk_code()
data = Test().detect_price_stk_code()
Result format
Filename: api/test/test_price_search.py
Line # Mem usage Increment Occurrences Line Contents
=============================================================
15 122.9 MiB 122.9 MiB 1 @profile
16 def detect_price_search(self):
17 122.9 MiB 0.0 MiB 1 start_date = '2024-01-01'
18 122.9 MiB 0.0 MiB 1 trade_volume = 200000000000
19 122.9 MiB 0.0 MiB 1 volume = None
20
...