Skip to content

Commit

Permalink
Update main.py
Browse files Browse the repository at this point in the history
  • Loading branch information
pdr21001 authored Apr 23, 2025
1 parent 1c1bdb2 commit a00fa21
Showing 1 changed file with 10 additions and 37 deletions.
47 changes: 10 additions & 37 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand All @@ -38,44 +30,34 @@ 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}")
return jsonify({'error': 'Internal Server Error'}), 500

@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/<int:pet_id>', methods=['GET'])
def get_pet(pet_id):
"""Retrieve a single pet by ID."""
try:
conn = get_db()
cursor = conn.cursor()
Expand All @@ -85,52 +67,43 @@ 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}")
return jsonify({'error': 'Internal Server Error'}), 500

@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)

0 comments on commit a00fa21

Please sign in to comment.