It is day 4 of working on my AI Tutor web app project. Today, I have learn something interesting while working with the database.
The context manager is both a design pattern and a protocol which enable us to efficiently manage our resource stop it from being waste.
To understand this, let me give you an intution from my project. For example, 50 students connects with my database to do something like generate roadmap or whatever they are up to then they leave. If the database connection for all 50 students are not closed then new students wouldn't be able to access my database to get there data or to do something. Yes, we can manually close the database but that's not how it should be done. So to do it automatically without you worrying about did i close the database there or here or where, you just use contextmanager..
from contextlib import contextmanager
@contextmanager
def manage_db():
db = Database()
try:
db.connect_to_db()
db.create_table()
yield db # Everything inside the 'with' block happens here
finally:
# This is GUARANTEED to run even if an error occurs above
db.close()
with manage_db() as db:
# Here we will perform our work or operations on database
Even if the with block gives error our try...finally handly it and close the database anyway....
Key banefits of using context manager are it is:
I tried to explain what I understand in context of python, FastAPI and sqlmodel. In different languages and framework it is called differently like Resource Acquisition Is Initialization(RAII), Scoped Resource Management or Disposables. But the main concept is same, preventing resource leakage and managing it efficiently. If you hear of this, do share what you understand and what I missed.....
No responses yet.