diff --git a/backend/main.py b/backend/main.py index 2f52d4e..865ba36 100644 --- a/backend/main.py +++ b/backend/main.py @@ -6,29 +6,21 @@ from flasgger import Swagger from utils import create_tables -# Initialize Flask app app = Flask(__name__) - Swagger(app) -# SQLite database file DATABASE = 'animal_shelter.db' -# Helper function to get a database connection def get_db(): - """Establish a connection to the SQLite database.""" conn = sqlite3.connect(DATABASE) - conn.row_factory = sqlite3.Row # Allows row access by column name + conn.row_factory = sqlite3.Row return conn -# Database initialization function to create tables and initial data def init_db(): - """Create tables and add initial data if they don't exist.""" if not os.path.exists(DATABASE): conn = get_db() create_tables(conn) - # Insert initial pet data for testing pets = [ ('Buddy', 'Dog', 'Golden Retriever', 3, 'Friendly', '/images/buddy.jpg', 'Available'), ('Whiskers', 'Cat', 'Siamese', 2, 'Independent', '/images/whiskers.jpg', 'Available'), @@ -38,30 +30,23 @@ def init_db(): ('Bella', 'Dog', 'Bulldog', 2, 'Gentle', '/images/bella.jpg', 'Available') ] - conn = get_db() cursor = conn.cursor() cursor.executemany(''' INSERT INTO animals (name, species, breed, age, personality, image_path, adoption_status) - VALUES (?, ?, ?, ?, ?, ?, ?) - ''', pets) + VALUES (?, ?, ?, ?, ?, ?, ?)''', pets) conn.commit() conn.close() -# API Routes @app.route('/api/pets', methods=['GET']) def get_pets(): - """Retrieve all pets.""" try: conn = get_db() cursor = conn.cursor() cursor.execute("SELECT * FROM animals") pets = cursor.fetchall() - - # Convert rows to a list of dictionaries pet_list = [dict(pet) for pet in pets] conn.close() - return jsonify(pet_list), 200 except sqlite3.Error as e: print(f"An error occurred: {e}") @@ -69,13 +54,10 @@ def get_pets(): @app.route('/', methods=['GET']) def home(): - """Home route to welcome users to the API.""" - return jsonify({'message': - 'Welcome to the Pet API! Visit /apidocs for the Swagger documentation.'}) + return jsonify({'message': 'Welcome to the Pet API! Visit /apidocs for the Swagger documentation.'}) @app.route('/api/pets/', methods=['GET']) def get_pet(pet_id): - """Retrieve a single pet by ID.""" try: conn = get_db() cursor = conn.cursor() @@ -85,10 +67,8 @@ def get_pet(pet_id): if pet is None: return jsonify({'error': 'Pet not found'}), 404 - # Convert the SQLite row object to a dictionary pet_dict = {key: pet[key] for key in pet.keys()} conn.close() - return jsonify(pet_dict), 200 except sqlite3.Error as e: print(f"An error occurred: {e}") @@ -96,41 +76,34 @@ def get_pet(pet_id): @app.route('/api/pets', methods=['POST']) def add_pet(): - """Add a new pet.""" try: pet_data = request.get_json() - - # Validate required fields required_fields = ['name', 'species', 'breed', 'age', 'personality'] + for field in required_fields: if field not in pet_data: return jsonify({'error': f'Missing required field: {field}'}), 400 conn = get_db() cursor = conn.cursor() - cursor.execute(''' INSERT INTO animals (name, species, breed, age, personality, image_path, adoption_status) - VALUES (?, ?, ?, ?, ?, ?, ?) - ''', (pet_data['name'], pet_data['species'], - pet_data['breed'], pet_data['age'], - pet_data['personality'], - pet_data.get('image_path', '/images/default.jpg'), - 'Available')) + VALUES (?, ?, ?, ?, ?, ?, ?)''', + (pet_data['name'], pet_data['species'], pet_data['breed'], + pet_data['age'], pet_data['personality'], + pet_data.get('image_path', '/images/default.jpg'), 'Available')) conn.commit() conn.close() - return jsonify({'message': 'Pet created successfully'}), 201 except sqlite3.Error as e: print(f"An error occurred: {e}") return jsonify({'error': 'Internal Server Error'}), 500 -# Initialize database on first run -@app.before_first_request def before_first_request(): - """Initialize the database before the first request.""" init_db() +app.before_request_funcs.setdefault(None, []).append(before_first_request) + if __name__ == "__main__": app.run(debug=True, use_reloader=False)