# app.py - COMPLETE VERSION import os from dotenv import load_dotenv from flask import Flask, jsonify, request import pymysql import pymysql.cursors from config import config # Load environment variables at the start load_dotenv() app = Flask(__name__) # Configure the app env = os.getenv('FLASK_ENV', 'development') app.config.from_object(config[env]) print(f"🔧 App configured for: {env}") print(f"📡 Will run on port: {app.config['FLASK_PORT']}") # Database configuration def get_db_connection(): db_config = { 'host': app.config['DB_HOST'], 'user': app.config['DB_USER'], 'password': app.config['DB_PASSWORD'], 'database': app.config['DB_NAME'], 'port': app.config['DB_PORT'], 'charset': 'utf8mb4', 'cursorclass': pymysql.cursors.DictCursor } try: return pymysql.connect(**db_config) except pymysql.Error as e: print(f"Database connection error: {e}") return None def init_users_table(): """Create users table if it doesn't exist""" conn = get_db_connection() if conn: try: with conn.cursor() as cursor: cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(80) UNIQUE NOT NULL, email VARCHAR(120) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') conn.commit() print("✅ Users table is ready") except Exception as e: print(f"Error creating users table: {e}") finally: conn.close() # Initialize the users table when app starts init_users_table() # Routes @app.route('/') def hello(): return jsonify({ "message": "WearWell API is running!", "port": app.config['FLASK_PORT'], "endpoints": { "health_check": "/health", "all_users": "/users", "get_user": "/users/", "add_user": "/users/add (POST)", "delete_user": "/users/delete/ (DELETE)", "web_interface": "/users/manage" } }) @app.route('/health') def health_check(): conn = get_db_connection() if conn: conn.close() return jsonify({"status": "healthy", "database": "connected"}) else: return jsonify({"status": "unhealthy", "database": "disconnected"}), 500 # User Management Routes @app.route('/users') def get_all_users(): """Get all users""" conn = get_db_connection() if not conn: return jsonify({"error": "Database connection failed"}), 500 try: with conn.cursor() as cursor: cursor.execute("SELECT * FROM users ORDER BY created_at DESC") users = cursor.fetchall() return jsonify({"users": users, "count": len(users)}) except Exception as e: return jsonify({"error": str(e)}), 500 finally: conn.close() @app.route('/users/') def get_user(user_id): """Get a specific user by ID""" conn = get_db_connection() if not conn: return jsonify({"error": "Database connection failed"}), 500 try: with conn.cursor() as cursor: cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,)) user = cursor.fetchone() if user: return jsonify({"user": user}) else: return jsonify({"error": "User not found"}), 404 except Exception as e: return jsonify({"error": str(e)}), 500 finally: conn.close() @app.route('/users/add', methods=['POST']) def add_user(): """Add a new user""" conn = get_db_connection() if not conn: return jsonify({"error": "Database connection failed"}), 500 try: # Check if request is JSON if not request.is_json: return jsonify({"error": "Content-Type must be application/json"}), 400 data = request.get_json() if not data or not data.get('username') or not data.get('email'): return jsonify({"error": "Username and email are required"}), 400 username = data['username'].strip() email = data['email'].strip() # Basic validation if len(username) < 3: return jsonify({"error": "Username must be at least 3 characters"}), 400 if '@' not in email: return jsonify({"error": "Invalid email format"}), 400 with conn.cursor() as cursor: cursor.execute( "INSERT INTO users (username, email) VALUES (%s, %s)", (username, email) ) conn.commit() user_id = cursor.lastrowid return jsonify({ "message": "User added successfully", "user_id": user_id, "username": username, "email": email }), 201 except pymysql.IntegrityError as e: if "username" in str(e): return jsonify({"error": "Username already exists"}), 400 elif "email" in str(e): return jsonify({"error": "Email already exists"}), 400 else: return jsonify({"error": "Database integrity error"}), 400 except Exception as e: return jsonify({"error": str(e)}), 500 finally: conn.close() @app.route('/users/delete/', methods=['DELETE']) def delete_user(user_id): """Delete a user by ID""" conn = get_db_connection() if not conn: return jsonify({"error": "Database connection failed"}), 500 try: with conn.cursor() as cursor: # First check if user exists cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,)) user = cursor.fetchone() if not user: return jsonify({"error": "User not found"}), 404 # Delete the user cursor.execute("DELETE FROM users WHERE id = %s", (user_id,)) conn.commit() return jsonify({ "message": "User deleted successfully", "deleted_user": { "id": user_id, "username": user['username'], "email": user['email'] } }) except Exception as e: return jsonify({"error": str(e)}), 500 finally: conn.close() @app.route('/users/update/', methods=['PUT']) def update_user(user_id): """Update a user's information""" conn = get_db_connection() if not conn: return jsonify({"error": "Database connection failed"}), 500 try: if not request.is_json: return jsonify({"error": "Content-Type must be application/json"}), 400 data = request.get_json() if not data or (not data.get('username') and not data.get('email')): return jsonify({"error": "At least username or email is required to update"}), 400 # Build update query dynamically based on provided fields update_fields = [] values = [] if 'username' in data and data['username']: update_fields.append("username = %s") values.append(data['username'].strip()) if 'email' in data and data['email']: update_fields.append("email = %s") values.append(data['email'].strip()) values.append(user_id) with conn.cursor() as cursor: cursor.execute( f"UPDATE users SET {', '.join(update_fields)} WHERE id = %s", values ) conn.commit() if cursor.rowcount == 0: return jsonify({"error": "User not found"}), 404 return jsonify({"message": "User updated successfully"}) except pymysql.IntegrityError as e: if "username" in str(e): return jsonify({"error": "Username already exists"}), 400 elif "email" in str(e): return jsonify({"error": "Email already exists"}), 400 else: return jsonify({"error": "Database integrity error"}), 400 except Exception as e: return jsonify({"error": str(e)}), 500 finally: conn.close() # Web Interface @app.route('/users/manage') def manage_users(): """Simple web interface to manage users""" return ''' User Management - WearWell

👥 User Management - WearWell

➕ Add New User

📋 Users List

Loading user count...

🔧 API Testing

Test the API endpoints directly:

'''