From b02c6c12528d033f7470b80f4beea97995f7a4c2 Mon Sep 17 00:00:00 2001 From: Fabio Scotto di Santolo Date: Thu, 1 Jul 2021 19:46:46 +0200 Subject: [PATCH] Gestione dei database con la struttura with --- database/__init__.py | 0 database/main.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 database/__init__.py create mode 100644 database/main.py diff --git a/database/__init__.py b/database/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/database/main.py b/database/main.py new file mode 100644 index 0000000..3239b68 --- /dev/null +++ b/database/main.py @@ -0,0 +1,42 @@ +class FakeCursor: + pass + + +class FakeConnection: + def __init__(self, configuration: dict) -> None: + self.__configuration = configuration + + def cursor(self): + return FakeCursor() + + +class UseDatabase: + def __init__(self, config: dict) -> None: + self.__configuration = config + + def __enter__(self) -> 'cursor': + print("Initializing DB connection...") + self.__connection = FakeConnection(self.__configuration) + self.__cursor = self.__connection.cursor() + return self.__cursor + + def __exit__(self, exc_type, exc_val, exc_tb) -> None: + """ + Python call this method when close resources + :param exc_type: + :param exc_val: + :param exc_tb: + :return: + """ + print("...Close resources") + print(f"{exc_type=}, {exc_val=}, {exc_tb=}") + + +def main(): + with UseDatabase({}) as my_cursor: + print("Execute 'with' body") + print(f"{my_cursor=}") + + +if __name__ == '__main__': + main()