diff --git a/crud_operation/.gitignore b/crud_operation/.gitignore new file mode 100644 index 00000000..f3eb67e6 --- /dev/null +++ b/crud_operation/.gitignore @@ -0,0 +1,209 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +test + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ diff --git a/crud_operation/LICENSE b/crud_operation/LICENSE new file mode 100644 index 00000000..d4b020a0 --- /dev/null +++ b/crud_operation/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Luckson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crud_operation/README.md b/crud_operation/README.md new file mode 100644 index 00000000..e4c35267 --- /dev/null +++ b/crud_operation/README.md @@ -0,0 +1,87 @@ +# User Management System (CLI) + +A lightweight **Command Line Interface (CLI)** application built with Python to manage user records using **CRUD** (Create, Read, Update, Delete) operations. This project features a dynamic typewriter effect with ANSI color support for enhanced user experience. + +--- + +## 🚀 Features + +* **Full CRUD Operations:** View, Add, Update, and Delete users. +* **Dynamic UI:** Includes a "typewriter" animation effect for console output. +* **Color-Coded Feedback:** + * 🟢 **Green:** Success messages. + * 🔴 **Red:** Error messages and exit alerts. +* **Input Validation:** Ensures only numeric inputs are processed for actions. +* **Error Handling:** Robust `try-except` blocks to prevent crashes during runtime. + +--- + +## 🛠️ Project Structure + +```text +├── main.py # Entry point of the application +├── crud/ +│ └── views.py # User model and view logic +└── services/ + └── action.py # Logic mapping inputs to CRUD functions + +``` + +--- + +## 💻 Installation & Usage + +1. **Clone the repository:** +```bash +git clone [https://github.com/yourusername/user-management-python.git](https://github.com/yourusername/user-management-python.git) +cd user-management-python + +``` + + +2. **Run the application:** +```bash +python main.py + +``` + +## 📖 Menu Options + +Upon launching, select an option by typing the corresponding number: + +| Option | Action | Description | +| --- | --- | --- | +| **1** | **Show users list** | Displays all registered users. | +| **2** | **Add user** | Opens a prompt to create a new user profile. | +| **3** | **Update user** | Modifies existing user details. | +| **4** | **Delete user** | Removes a user from the system. | +| **5** | **Quit** | Safely closes the application. | + +--- + +## ⚙️ Technical Highlights + +### Visual Effects + +The system uses the `sys.stdout` buffer to print characters one by one for a typewriter effect, combined with **ANSI escape codes** for coloring: + +* **Green (`\033[92m`)**: Used for successful operations. +* **Red (`\033[91m`)**: Used for errors and exit messages. + +### Logic Flow + +The program verifies that the input is a digit before processing, preventing common input errors. + +```python +if action.isdigit(): + actions(action, User) +else: + print("Enter the action number.") + +``` + +--- + +## 📝 License + +This project is open-source and available under the **MIT License**. \ No newline at end of file diff --git a/crud_operation/crud/__init__.py b/crud_operation/crud/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/crud_operation/crud/db.py b/crud_operation/crud/db.py new file mode 100644 index 00000000..3f103c4b --- /dev/null +++ b/crud_operation/crud/db.py @@ -0,0 +1,7 @@ +import sqlite3 + +def db_connection(): + con = sqlite3.connect("db/users.db") + cursor = con.cursor() + + return con, cursor diff --git a/crud_operation/crud/models.py b/crud_operation/crud/models.py new file mode 100644 index 00000000..ab4ac0de --- /dev/null +++ b/crud_operation/crud/models.py @@ -0,0 +1,20 @@ +from crud.db import db_connection + +class Model: + def user(self): + con, cursor = db_connection() + + cursor.execute( + """ + CREATE TABLE IF NOT EXISTS Users( + id INTEGER PRIMARY KEY AUTOINCREMENT, + first_name TEXT NOT NULL, + last_name TEXT NOT NULL, + age INTEGER NOT NULL, + email TEXT NOT NULL, + UNIQUE(email) + ) + """ + ) + + con.commit() diff --git a/crud_operation/crud/test.py b/crud_operation/crud/test.py new file mode 100644 index 00000000..7aff256f --- /dev/null +++ b/crud_operation/crud/test.py @@ -0,0 +1,50 @@ +import sqlite3 + +con = sqlite3.connect("users.db") +cursor = con.cursor() + +cursor.execute( + """ + CREATE TABLE IF NOT EXISTS Users( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + age REAL NOT NULL, + email TEXT UNIQUE NOT NULL + ) + """ +) + +cursor.execute( + """ + CREATE TABLE IF NOT EXISTS Post( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + post TEXT NOT NULL, + FOREIGN KEY(user_id) REFERENCES Users(id) + ) + """ +) + +cursor.execute( + "INSERT OR IGNORE INTO Users (name, age, email) VALUES (?,?,?)", + ('wilondja', 52, 'wilondja@gmail.com') +) + +cursor.execute( + "INSERT INTO Post(user_id, post) VALUES (?,?)", (1, "Nous sommes les enfants de Dieu.") +) +cursor.execute("PRAGMA foreign_keys=ON;") + +con.commit() + +cursor.execute( + "SELECT Users.name, Post.post FROM Post INNER JOIN Users ON Post.user_id = Users.id WHERE Post.user_id=?", (1,) +) + +result = cursor.fetchone() + +print(result) + + +cursor.close() +con.close() \ No newline at end of file diff --git a/crud_operation/crud/views.py b/crud_operation/crud/views.py new file mode 100644 index 00000000..31a7b6be --- /dev/null +++ b/crud_operation/crud/views.py @@ -0,0 +1,92 @@ +from crud.db import db_connection +from crud.models import Model +from services.color import change_color + +Model().user() + +class User: + def __init__(self, first_name, last_name, age, email): + self.first_name = first_name + self.last_name = last_name + self.age = age + self.email = email + + def insert_user(self): + con, cursor = db_connection() + + clean = self.clean_data() + if clean: + cursor.execute( + "INSERT OR IGNORE INTO Users(first_name, last_name, age, email) VALUES (?,?,?,?)", + (self.first_name, self.last_name, self.age, self.email) + ) + con.commit() + change_color("\n ===> User added successfully", "\033[92m") + + @staticmethod + def select_user(): + _, cursor = db_connection() + + cursor.execute("SELECT* FROM Users") + users = cursor.fetchall() + return users + + def update_user(self): + con, cursor = db_connection() + user_id = User.user_id('update') + + cursor.execute( + "SELECT * FROM Users WHERE id=?", + (user_id,) + ) + user = cursor.fetchone() + + new_age = self.age if self.age not in (None, "") else user[3] + if isinstance(new_age, str) and new_age.isdigit(): + new_age = int(new_age) + + if user: + cursor.execute( + "UPDATE Users SET first_name=?, last_name=?, age=?, email=? WHERE id=?", + ( + self.first_name or user[1], + self.last_name or user[2],new_age, + self.email or user[4], user_id) + ) + con.commit() + change_color("\n ===> User modified successfully", "\033[92m") + else: + change_color("\n ===> User doesn't exist.", "\033[91m") + + @staticmethod + def delete_user(): + con, cursor = db_connection() + user_id = User.user_id('delete') + users = User.select_user() + + user = [user for user in users if user[0] == user_id] + if user: + cursor.execute( + "DELETE FROM Users WHERE id=?",(user_id,) + ) + con.commit() + change_color("\n ===> User delete successfully", "\033[92m") + else: + change_color("\n ===> Enter a valid id", "\033[91m") + + @staticmethod + def user_id(a: str): + try: + user_id = int(input(f"Enter a user_id to {a} : ")) + return user_id + except: + change_color("Id can be a number.", "\033[91m") + + def clean_data(self): + if not self.age.isdigit(): + change_color("\n ===> Enter the action number") + return False + elif not self.email.endswith("@gmail.com"): + change_color("\n ===> Enter a valid email.", "\033[91m") + return False + return True diff --git a/crud_operation/db/users.db b/crud_operation/db/users.db new file mode 100644 index 00000000..e3a5fcfa Binary files /dev/null and b/crud_operation/db/users.db differ diff --git a/crud_operation/main.py b/crud_operation/main.py new file mode 100644 index 00000000..5c1e991f --- /dev/null +++ b/crud_operation/main.py @@ -0,0 +1,37 @@ + +""" + USER MANAGEMENT +""" + +from crud.views import User +from services.action import actions +from services.color import change_color + + +while True: + print("\033[96m") + print( + """ + ========= USER MANAGEMENT ========== + + 1. Show users list + 2. Add user + 3. Update user + 4. Delete user + 5. Quite + """ + ) + + try: + action = input("Enter an action to perform : ") + + if action == '5': + print("==== PROGRAM ENDED ====") + break + + if action.isdigit(): + actions(action, User) + else: + change_color("Enter the action number.", "\033[91m") + except Exception as e: + print(str(e)) \ No newline at end of file diff --git a/crud_operation/services/action.py b/crud_operation/services/action.py new file mode 100644 index 00000000..799062a9 --- /dev/null +++ b/crud_operation/services/action.py @@ -0,0 +1,40 @@ +from services.color import change_color + +def inputs(): + first_name = input("Fist name: ") + last_name = input("Last name: ") + age = input("Age: ") + email = input("Email: ") + + return ( + first_name, + last_name, + age, + email + ) + +def actions(action, User): + if action == '1': + users = User.select_user() + print(f"\n ==> Users list <=== \n") + if users: + for user in users: + print(f"{user[0]} {user[1]} {user[2]} {user[3]} {user[4]}") + else: + print(f"Data is emtpy => {users}") + + elif action == '2': + user = inputs() + if user: + User(*user).insert_user() + else: + change_color("\n ===> Incorect infos", "\033[0m") + elif action == '3': + user = inputs() + if user: + User(*user).update_user() + + elif action == '4': + User.delete_user() + else: + change_color("\n ===> Enter a valid action.", "\033[0m") \ No newline at end of file diff --git a/crud_operation/services/color.py b/crud_operation/services/color.py new file mode 100644 index 00000000..3e49a966 --- /dev/null +++ b/crud_operation/services/color.py @@ -0,0 +1,17 @@ +import sys +import time + +# ANSI CODE +GREEN = "\033[92m" +RED = "\033[91m" +RESET = "\033[0m" + +def change_color(text, color_code=RESET): + sys.stdout.write(color_code) + + for t in text: + sys.stdout.write(t) + sys.stdout.flush() + time.sleep(0.05) + + sys.stdout.write(RESET + "\n")