├── LICENSE ├── README.md ├── application.db ├── create_db.py ├── requirements.txt ├── sqlite.py ├── sqlite_context.py ├── sqlite_context_async.py └── sqlite_context_decorator.py /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 ArjanCodes 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Building A Custom Context Manager In Python: A Closer Look 2 | 3 | Context managers in Python allow you to robustly control setup and teardown of resources. In this video, I'll show you how to use them and I'll cover several ways to create your own. 4 | 5 | Here's the link to the video: https://youtu.be/14z_Tf3p2Mw. 6 | -------------------------------------------------------------------------------- /application.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArjanCodes/2022-context-managers/3e8ddbe57242f0adeb6587c0e5e7361b5f42f41e/application.db -------------------------------------------------------------------------------- /create_db.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | con = sqlite3.connect('application.db') 3 | 4 | cur = con.cursor() 5 | 6 | # Create table 7 | cur.execute('''CREATE TABLE blogs 8 | (id text not null primary key, date text, title text, content text, public integer)''') 9 | 10 | # Insert a few rows of data 11 | cur.execute("INSERT INTO blogs VALUES ('first-blog', '2021-03-07', 'My first blog' ,'Some content', 1)") 12 | cur.execute("INSERT INTO blogs VALUES ('private-blog', '2021-03-07', 'Secret blog' ,'This is a secret', 0)") 13 | 14 | # Save (commit) the changes 15 | con.commit() 16 | 17 | # We can also close the connection if we are done with it. 18 | # Just be sure any changes have been committed or they will be lost. 19 | con.close() -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Python: 3.9.9 2 | aiosqlite -------------------------------------------------------------------------------- /sqlite.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sqlite3 3 | 4 | 5 | def main(): 6 | logging.basicConfig(level=logging.INFO) 7 | connection = sqlite3.connect("application.db") 8 | try: 9 | cursor = connection.cursor() 10 | cursor.execute("SELECT * FROM blogs") 11 | logging.info(cursor.fetchall()) 12 | finally: 13 | connection.close() 14 | 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /sqlite_context.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sqlite3 3 | 4 | 5 | class SQLite: 6 | def __init__(self, file_name: str): 7 | self.file_name = file_name 8 | self.connection = sqlite3.connect(self.file_name) 9 | 10 | def __enter__(self): 11 | logging.info("Calling __enter__") 12 | return self.connection.cursor() 13 | 14 | def __exit__(self, error: Exception, value: object, traceback: object): 15 | logging.info("Calling __exit__") 16 | self.connection.commit() 17 | self.connection.close() 18 | 19 | 20 | def main(): 21 | logging.basicConfig(level=logging.INFO) 22 | with SQLite(file_name="application.db") as cursor: 23 | cursor.execute("SELECT * FROM blogs") 24 | logging.info(cursor.fetchall()) 25 | 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /sqlite_context_async.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | import aiosqlite 5 | 6 | 7 | async def main(): 8 | logging.basicConfig(level=logging.INFO) 9 | # async with aiosqlite.connect("application.db") as db: 10 | # async with db.execute("SELECT * FROM blogs") as cursor: 11 | # logging.info(await cursor.fetchall()) 12 | db = await aiosqlite.connect("application.db") 13 | cursor = await db.execute("SELECT * FROM blogs") 14 | logging.info(await cursor.fetchall()) 15 | 16 | 17 | if __name__ == "__main__": 18 | asyncio.run(main()) 19 | -------------------------------------------------------------------------------- /sqlite_context_decorator.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sqlite3 3 | from contextlib import contextmanager 4 | 5 | 6 | @contextmanager 7 | def open_db(file_name: str): 8 | conn = sqlite3.connect(file_name) 9 | try: 10 | logging.info("Creating connection") 11 | yield conn.cursor() 12 | finally: 13 | logging.info("Closing connection") 14 | conn.commit() 15 | conn.close() 16 | 17 | 18 | def main(): 19 | logging.basicConfig(level=logging.INFO) 20 | with open_db(file_name="application.db") as cursor: 21 | cursor.execute("SELECT * FROM blogs") 22 | logging.info(cursor.fetchall()) 23 | 24 | 25 | if __name__ == "__main__": 26 | main() 27 | --------------------------------------------------------------------------------