TelenkovDmitry hai 6 meses
pai
achega
3d5e3f11c4

+ 3 - 0
.vscode/settings.json

@@ -0,0 +1,3 @@
+{
+    "editor.rulers": [80]
+}

+ 0 - 0
courses/python_oop/descriptor/desc_1.py


+ 0 - 0
courses/python_oop/manager/context.py → courses/python_oop/manager/context_1.py


+ 60 - 0
courses/python_oop/manager/context_2.py

@@ -0,0 +1,60 @@
+import sqlite3
+
+def test_sqlite():
+
+    try:
+        con = sqlite3.connect("mydb.sqlite")
+    except sqlite3.Error as er:
+        print("Error connecting to database:", er)
+
+    cur = con.cursor()
+    sql_query = "INSERT INTO user VALUES(?, ?)"
+    sql_data = ("John", "MacDonald")
+
+    try:
+        cur.execute(sql_query, sql_data)
+        con.commit()
+    except sqlite3.Error as er:
+        print('SQLite error: %s' % (' '.join(er.args)))
+        print("Exception class is: ", er.__class__)
+        print('SQLite traceback: ')
+    finally:
+        con.close()
+
+class DatabaseManager:
+    def __init__(self, db_name):
+        self.db_name = db_name
+
+    def __enter__(self):
+        try:
+            self.conn = sqlite3.connect(self.db_name)
+        except sqlite3.Error as e:
+            print("Error connecting to database:", e)
+            return None
+        else:
+            return self.conn
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        try:
+            self.conn.close()
+        except AttributeError:
+            print("Database connection not established")
+        except sqlite3.Error as e:
+            print("An error occured while closing the database connection: ", e)
+    
+
+def test_context():
+    with DatabaseManager("mydb.sqlite") as conn:
+        if conn:
+            cur = conn.cursor()
+            sql_query = "INSERT INTO user VALUES(?, ?)"
+            sql_data = ("Jogn", "MacDonald")
+            cur.execute(sql_query, sql_data)
+            conn.commit()
+
+def main():
+    # test_sqlite()
+    test_context()
+
+if __name__ == '__main__':
+    main()

+ 34 - 0
courses/python_oop/manager/context_3.py

@@ -0,0 +1,34 @@
+import time
+
+def calculate():
+    for i in range(10000):
+        2 ** 2123
+
+# Расчет время выполнения функций
+
+class Timer:
+    def __enter__(self):
+        self.start = time.time()
+        self.end = 0.0
+        return lambda: self.end - self.start
+
+    def __exit__(self, *args):
+        self.end = time.time()
+
+
+def main():
+    with Timer() as my_timer:
+        time.sleep(0.6)
+    print(my_timer())
+
+    with Timer() as my_timer2:
+        time.sleep(1.5)
+    print(my_timer2())
+
+    with Timer() as my_timer3:
+        calculate()
+    print(my_timer3())
+
+
+if __name__ == '__main__':
+    main()

+ 32 - 0
courses/python_oop/manager/context_4.py

@@ -0,0 +1,32 @@
+from contextlib import contextmanager
+import time
+
+@contextmanager
+def my_context_manager():
+    print("Начало контекстного манеджера ...")
+    yield "Ух ты как круто!"
+    print("Конец контекстного менеджера...")
+
+@contextmanager
+def timer():
+    start = time.time()
+    yield "Работает контекстный менеджер"
+    print(time.time() - start)
+
+
+def calculate():
+    for i in range(10000):
+        2 ** 2123
+
+
+def main():
+    # Тест декоратора
+    # with my_context_manager() as phrase:
+    #     print(phrase)
+
+    with timer() as t:
+        print(t)
+        calculate()
+
+if __name__ == '__main__':
+    main()

+ 25 - 0
courses/python_oop/manager/context_5.py

@@ -0,0 +1,25 @@
+import os
+import contextlib
+# import mysql.connector
+
+@contextlib.contextmanager
+def get_mysql_conn(db):
+    """
+    Context manager to automatically close DB connection.
+    We retrieve credenrials from Enviroment variables
+    """
+    conn = mysql.connector.connect(host = os.environ.get('MYSQL_HOST'),
+        user=os.environ.get('MYSQL_USER'), password=os.environ.get('MYSQL_PWD'), 
+        database=db)
+
+    try:
+        yield conn
+    finally:
+        conn.close()
+
+
+def main():
+    pass
+
+if __name__ == '__main__':
+    main()

+ 0 - 0
courses/python_oop/manager/mydb.sqlite