From bfa39c4e9238989cc354e7a69ea484adc80cd954 Mon Sep 17 00:00:00 2001 From: Prince D Rusweka Rwabongoya Date: Wed, 23 Apr 2025 18:50:55 -0400 Subject: [PATCH] Update main.py --- backend/main.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/backend/main.py b/backend/main.py index 865ba36..435fc78 100644 --- a/backend/main.py +++ b/backend/main.py @@ -12,11 +12,13 @@ DATABASE = 'animal_shelter.db' def get_db(): + """Establish a connection to the SQLite database.""" conn = sqlite3.connect(DATABASE) conn.row_factory = sqlite3.Row return conn def init_db(): + """Initialize the database and insert sample data if not already present.""" if not os.path.exists(DATABASE): conn = get_db() create_tables(conn) @@ -40,6 +42,7 @@ def init_db(): @app.route('/api/pets', methods=['GET']) def get_pets(): + """Retrieve and return all pets from the database.""" try: conn = get_db() cursor = conn.cursor() @@ -54,10 +57,14 @@ def get_pets(): @app.route('/', methods=['GET']) def home(): - return jsonify({'message': 'Welcome to the Pet API! Visit /apidocs for the Swagger documentation.'}) + """Return a welcome message for the API.""" + 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 pet by its ID.""" try: conn = get_db() cursor = conn.cursor() @@ -76,6 +83,7 @@ def get_pet(pet_id): @app.route('/api/pets', methods=['POST']) def add_pet(): + """Add a new pet to the database.""" try: pet_data = request.get_json() required_fields = ['name', 'species', 'breed', 'age', 'personality'] @@ -101,6 +109,7 @@ def add_pet(): return jsonify({'error': 'Internal Server Error'}), 500 def before_first_request(): + """Run once before the first request to initialize the database.""" init_db() app.before_request_funcs.setdefault(None, []).append(before_first_request)