From 1d75ffde8721f89884411300ade82e743bc9033a Mon Sep 17 00:00:00 2001 From: Ganesh Hubale Date: Tue, 8 Oct 2024 16:00:29 +0530 Subject: [PATCH 1/2] Added Proper exception handling for database methods Signed-off-by: Ganesh Hubale --- README.rst | 5 +- pygenpass/database.py | 136 +++++++++++++++++++++++++++++------------- pygenpass/password.py | 9 +++ 3 files changed, 106 insertions(+), 44 deletions(-) diff --git a/README.rst b/README.rst index a934676..685a1ce 100644 --- a/README.rst +++ b/README.rst @@ -25,13 +25,16 @@ How to run project? $ git clone https://github.com/paint-it/pygenpass.git -* Install using pip or setup.py +* Install using pip .. code-block:: bash $ pip install pygenpass +* Install using setup file +.. code-block:: bash + $ pip3 install setuptools $ python3 setup.py install * Use command **pygenpass** diff --git a/pygenpass/database.py b/pygenpass/database.py index ba8965c..4a08bc3 100644 --- a/pygenpass/database.py +++ b/pygenpass/database.py @@ -22,7 +22,7 @@ import sqlite3 # library for database from termcolor import colored - +import sys class DatabaseConnection: """ Class of database entries for user's information.""" @@ -30,70 +30,120 @@ class DatabaseConnection: def __init__(self): """Used to create database and then to connect with generated databse file Checked for table is created? if not then created as per required values """ - self.con = sqlite3.connect("generated_password.db") - self.cursor_obj = self.con.cursor() - self.cursor_obj.execute( - """CREATE TABLE IF NOT EXISTS passwords( - id integer PRIMARY KEY,portal_name text NOT NULL UNIQUE, password varchar, - creation_date varchar, email varchar, portal_url varchar) - """ - ) - self.con.commit() + try: + self.con = sqlite3.connect("generated_password.db") + self.cursor_obj = self.con.cursor() + self.cursor_obj.execute( + """CREATE TABLE IF NOT EXISTS passwords( + id integer PRIMARY KEY,portal_name text NOT NULL UNIQUE, password varchar, + creation_date varchar, email varchar, portal_url varchar) + """ + ) + self.con.commit() + except sqlite3.Error as e: + # Catch any SQLite error and print the error message + print(f"Database error occurred: {e}") + sys.exit(1) # Exit the program if a database error occurs + + except Exception as e: + # Catch any other exceptions and print the error message + print(f"An error occurred: {e}") + sys.exit(1) # Exit the program if an unexpected error occurs + def insert_data(self, portal_name, password, creation_date, email, portal_url): """Adding values into database""" - self.password = password - self.creation_date = creation_date - self.email = email - self.portal_name = portal_name - self.portal_url = portal_url try: self.cursor_obj.execute( """INSERT INTO passwords (portal_name, password, creation_date, email, portal_url) VALUES (?, ?, ?, ?, ?)""", - (self.portal_name, self.password, self.creation_date, self.email, self.portal_url), + (portal_name, password, creation_date, email, portal_url), ) + self.con.commit() except sqlite3.IntegrityError: print( - colored("Already exists with the same name. Try with another Portal_name", "green") + colored(f"Error: A record with the portal name '{portal_name}' already exists.", "green") ) - self.con.commit() + + except sqlite3.Error as e: + print(f"Database error occurred while inserting data: {e}") + + except Exception as e: + print(f"An unexpected error occurred: {e}") def delete_data(self, portal_name): """Deleting values from database""" - self.portal_name = portal_name - self.cursor_obj.execute( - """DELETE from passwords where portal_name = ?""", (self.portal_name,) - ) - self.con.commit() + try: + self.cursor_obj.execute( + """DELETE from passwords where portal_name = ?""", (portal_name,) + ) + self.con.commit() + print(f"Data for portal '{portal_name}' deleted successfully.") + + except sqlite3.Error as e: + print(f"Database error occurred while deleting data: {e}") + + except Exception as e: + print(f"An unexpected error occurred: {e}") def update_data(self, portal_name, password): """Updating values in database""" - self.portal_name = portal_name - self.password = password - self.cursor_obj.execute( - """UPDATE passwords SET password =? WHERE portal_name =?""", - (self.password, self.portal_name), - ) - self.con.commit() + try: + self.cursor_obj.execute( + """UPDATE passwords SET password =? WHERE portal_name =?""", + (password, portal_name), + ) + self.con.commit() + print(f"Password for portal '{portal_name}' updated successfully.") + + except sqlite3.Error as e: + print(f"Database error occurred while updating data: {e}") + + except Exception as e: + print(f"An unexpected error occurred: {e}") def show_data(self, portal_name): """All inserted data will showed""" - self.portal_name = portal_name - self.cursor_obj.execute( - """SELECT password FROM passwords WHERE portal_name=?""", (self.portal_name,) - ) - rows = self.cursor_obj.fetchall() - - for row in rows: - return row[0] + try: + self.cursor_obj.execute( + """SELECT password FROM passwords WHERE portal_name=?""", (portal_name,) + ) + row = self.cursor_obj.fetchone() - self.con.commit() + if row: + return row[0] + else: + print(f"No data found for portal '{portal_name}'.") + return None + except sqlite3.Error as e: + print(f"Database error occurred while fetching data: {e}") + + except Exception as e: + print(f"An unexpected error occurred: {e}") def show_all_data(self): """Showing all data saved in database""" - self.cursor_obj.execute("""SELECT * FROM passwords""") - rows = self.cursor_obj.fetchall() - return rows - self.con.commit() + try: + self.cursor_obj.execute("""SELECT * FROM passwords""") + rows = self.cursor_obj.fetchall() + return rows + + except sqlite3.Error as e: + print(f"Database error occurred while fetching all data: {e}") + + except Exception as e: + print(f"An unexpected error occurred: {e}") + + def close_connection(self): + """Safely close the database connection.""" + try: + if self.con: + self.con.close() + print("Database connection closed successfully.") + + except sqlite3.Error as e: + print(f"Error closing the database connection: {e}") + + except Exception as e: + print(f"An unexpected error occurred while closing the connection: {e}") diff --git a/pygenpass/password.py b/pygenpass/password.py index a82ef97..d44258c 100644 --- a/pygenpass/password.py +++ b/pygenpass/password.py @@ -50,6 +50,8 @@ def all(): for row in all_pass: table.append_row([row[0], row[1], row[2], row[3], row[4], row[5]]) print(table) + db_obj.close_connection() + @click.command(help="Delete password") @@ -61,6 +63,7 @@ def delete(): print("No records found") else: db_obj.delete_data(portal_name=portal_name) + db_obj.close_connection() @click.command(help="Update password") @@ -73,6 +76,7 @@ def modify(): else: mod = click.prompt("Enter new password", default="None", hide_input=True) db_obj.update_data(portal_name=portal_name, password=mod) + db_obj.close_connection() @click.command(help="Add existing passwords") @@ -90,6 +94,8 @@ def add(): email=email, portal_url=portal_url, ) + db_obj.close_connection() + @click.command(help="Create new password") @@ -107,6 +113,8 @@ def create(): email=email, portal_url=portal_url, ) + db_obj.close_connection() + @click.command(help="Show password") @@ -117,3 +125,4 @@ def show(): print(colored("No records found", "green")) else: print(spass) + db_obj.close_connection() From 1571a36b7cb7348008ae7359285cdf787a64bbea Mon Sep 17 00:00:00 2001 From: Ganesh Hubale Date: Tue, 8 Oct 2024 16:07:57 +0530 Subject: [PATCH 2/2] Reformatted code using black tool Signed-off-by: Ganesh Hubale --- .github/workflows/main.yml | 2 +- .pre-commit-config.yaml | 78 ++++++++++++++++++++------------------ pygenpass/database.py | 27 +++++++------ pygenpass/password.py | 4 +- setup.cfg | 5 ++- setup.py | 4 +- 6 files changed, 64 insertions(+), 56 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 9477373..7a4bdf1 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -13,7 +13,7 @@ jobs: - name: Setup python uses: actions/setup-python@v1 with: - python-version: '3.7' + python-version: '3.9' architecture: 'x64' - name: Pre-Commit Checks diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e46f488..23c7bcf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,38 +1,42 @@ repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.4.0 - hooks: - - id: trailing-whitespace - name: Trim Trailing Whitespace - language_version: python3 - - id: end-of-file-fixer - name: File Ending - language_version: python3 - - id: debug-statements - name: Debug Statments - language_version: python3 - - id: flake8 - name: Flake8 - language_version: python3 - verbose: true - - id: check-yaml -- repo: https://github.com/asottile/reorder_python_imports - rev: v1.8.0 - hooks: - - id: reorder-python-imports - name: Reorder Python Imports - language_version: python3 -- repo: https://github.com/psf/black - rev: 19.10b0 - hooks: - - id: black - name: Formate with Black - args: [--safe, --quiet, --line-length, "100"] - language_version: python3 - require_serial: true -- repo: https://github.com/asottile/pyupgrade - rev: v1.25.2 - hooks: - - id: pyupgrade - name: Python Package Checks - language_version: python3 + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v2.4.0 + hooks: + - id: trailing-whitespace + name: Trim Trailing Whitespace + language_version: python3.9 # Updated to Python 3.9 + - id: end-of-file-fixer + name: File Ending + language_version: python3.9 # Updated to Python 3.9 + - id: debug-statements + name: Debug Statements + language_version: python3.9 # Updated to Python 3.9 + - id: flake8 + name: Flake8 + language_version: python3.9 # Updated to Python 3.9 + verbose: true + - id: check-yaml + name: Check YAML + + - repo: https://github.com/asottile/reorder_python_imports + rev: v3.7.0 + hooks: + - id: reorder-python-imports + name: Reorder Python Imports + language_version: python3.9 # Updated to Python 3.9 + + - repo: https://github.com/psf/black + rev: 22.12.0 # Ensure this version supports Python 3.9 + hooks: + - id: black + name: Format with Black + args: [--safe, --quiet, --line-length, "100"] + language_version: python3.9 # Updated to Python 3.9 + require_serial: true + + - repo: https://github.com/asottile/pyupgrade + rev: v3.10.0 + hooks: + - id: pyupgrade + name: Python Package Checks + language_version: python3.9 # Updated to Python 3.9 diff --git a/pygenpass/database.py b/pygenpass/database.py index 4a08bc3..bc5be2a 100644 --- a/pygenpass/database.py +++ b/pygenpass/database.py @@ -20,16 +20,17 @@ SOFTWARE. """ import sqlite3 # library for database +import sys from termcolor import colored -import sys + class DatabaseConnection: - """ Class of database entries for user's information.""" + """Class of database entries for user's information.""" def __init__(self): """Used to create database and then to connect with generated databse file - Checked for table is created? if not then created as per required values """ + Checked for table is created? if not then created as per required values""" try: self.con = sqlite3.connect("generated_password.db") self.cursor_obj = self.con.cursor() @@ -40,7 +41,7 @@ def __init__(self): """ ) self.con.commit() - except sqlite3.Error as e: + except sqlite3.Error as e: # Catch any SQLite error and print the error message print(f"Database error occurred: {e}") sys.exit(1) # Exit the program if a database error occurs @@ -50,7 +51,6 @@ def __init__(self): print(f"An error occurred: {e}") sys.exit(1) # Exit the program if an unexpected error occurs - def insert_data(self, portal_name, password, creation_date, email, portal_url): """Adding values into database""" try: @@ -63,12 +63,15 @@ def insert_data(self, portal_name, password, creation_date, email, portal_url): self.con.commit() except sqlite3.IntegrityError: print( - colored(f"Error: A record with the portal name '{portal_name}' already exists.", "green") + colored( + f"Error: A record with the portal name '{portal_name}' already exists.", + "green", + ) ) except sqlite3.Error as e: print(f"Database error occurred while inserting data: {e}") - + except Exception as e: print(f"An unexpected error occurred: {e}") @@ -99,7 +102,7 @@ def update_data(self, portal_name, password): except sqlite3.Error as e: print(f"Database error occurred while updating data: {e}") - + except Exception as e: print(f"An unexpected error occurred: {e}") @@ -118,7 +121,7 @@ def show_data(self, portal_name): return None except sqlite3.Error as e: print(f"Database error occurred while fetching data: {e}") - + except Exception as e: print(f"An unexpected error occurred: {e}") @@ -131,7 +134,7 @@ def show_all_data(self): except sqlite3.Error as e: print(f"Database error occurred while fetching all data: {e}") - + except Exception as e: print(f"An unexpected error occurred: {e}") @@ -141,9 +144,9 @@ def close_connection(self): if self.con: self.con.close() print("Database connection closed successfully.") - + except sqlite3.Error as e: print(f"Error closing the database connection: {e}") - + except Exception as e: print(f"An unexpected error occurred while closing the connection: {e}") diff --git a/pygenpass/password.py b/pygenpass/password.py index d44258c..18f2f43 100644 --- a/pygenpass/password.py +++ b/pygenpass/password.py @@ -28,6 +28,7 @@ from pygenpass.database import DatabaseConnection + db_obj = DatabaseConnection() table = BeautifulTable() table.left_border_char = "|" @@ -53,7 +54,6 @@ def all(): db_obj.close_connection() - @click.command(help="Delete password") def delete(): """used to delete existing password""" @@ -97,7 +97,6 @@ def add(): db_obj.close_connection() - @click.command(help="Create new password") def create(): """Used for taking input from user to create password""" @@ -116,7 +115,6 @@ def create(): db_obj.close_connection() - @click.command(help="Show password") def show(): portal_name = click.prompt("Enter portal name", default="None") diff --git a/setup.cfg b/setup.cfg index 54183c7..50516cb 100644 --- a/setup.cfg +++ b/setup.cfg @@ -16,6 +16,7 @@ classifiers = Programming Language :: Python Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 Environment :: Console Topic :: Internet Topic :: Utilities @@ -24,11 +25,11 @@ classifiers = zip_safe = false include_package_data = true packages = find: -python_requires = >= 3.6 +python_requires = >= 3.8 setup_requires = setuptools_scm install_requires = beautifultable - click + click >=8.1.0 diceware termcolor diff --git a/setup.py b/setup.py index f446046..4ca6776 100644 --- a/setup.py +++ b/setup.py @@ -1,3 +1,5 @@ from setuptools import setup -setup(use_scm_version=True,) +setup( + use_scm_version=True, +)