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 e90d151 commit bfa39c4
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
Expand All @@ -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/<int:pet_id>', methods=['GET'])
def get_pet(pet_id):
"""Retrieve a pet by its ID."""
try:
conn = get_db()
cursor = conn.cursor()
Expand All @@ -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']
Expand All @@ -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)
Expand Down

0 comments on commit bfa39c4

Please sign in to comment.