from flask import g from sqlite3 import connect, Connection, Cursor import shutil def get_db(): db = getattr(g, "_database", None) if db is None: db = g._database = connect("/data/tables.db") return db class SmartCursor: connection: Connection curosr: Cursor autoClose: bool def __init__(self, cursor: Cursor = None, connection: Connection = None): self.cursor = cursor self.connection = connection self.autoClose = False def __enter__(self): if self.cursor == None: self.cursor = self.connection.cursor() self.autoClose = True return self.cursor def __exit__(self, exc_type, exc_value, traceback): if self.autoClose: self.cursor.close()