A context manager packages setup and cleanup around a with block. For database work, it opens a SQLite connection before the block and commits and closes it afterward, avoiding repeated manual resource handling. section 5.3.4
import sqlite3
class DatabaseConnection:
def __init__(self, db_path):
self.db_path = db_path
def __enter__(self):
self.connection = sqlite3.connect(self.db_path)
return self.connection.cursor()
def __exit__(self):
self.connection.commit()
self.connection.close()
This compact implementation stores the database path, opens SQLite in __enter__, returns a cursor to the block, then commits and closes the connection in __exit__. section 5.3.4
Using a connection in a Flask route
A route can keep database lifetime local to the query: with DatabaseConnection(db_path) as cursor: questions = Questions(cursor) data = questions.fetch_data() return render_template('index.html', data=data) The Questions object receives the cursor, fetches the records, and leaves the connection to the context manager for cleanup. section 5.3.5
Review the implementation before reusing it:
- Confirm that __enter__ returns the object the block needs; this implementation returns a cursor rather than the connection. section 5.3.4
- Check the transaction policy: the shown __exit__ commits every completed block before closing the connection. section 5.3.4
- Reuse the connection wrapper across application code so database access remains easier to test and extend. section 5.3.5



