-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathapp.py
More file actions
83 lines (69 loc) · 2.36 KB
/
app.py
File metadata and controls
83 lines (69 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import os
from typing import Dict, List, Any, Optional
from flask import Flask, jsonify, request, Response
from models import init_db, db, Dog, Breed
# Get the server directory path
base_dir: str = os.path.abspath(os.path.dirname(__file__))
app: Flask = Flask(__name__)
db_path: str = os.environ.get('DATABASE_PATH', os.path.join(base_dir, 'dogshelter.db'))
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize the database with the app
init_db(app)
@app.route('/api/dogs', methods=['GET'])
def get_dogs() -> Response:
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 6, type=int)
page = max(1, page)
per_page = max(1, min(per_page, 100))
query = db.session.query(
Dog.id,
Dog.name,
Breed.name.label('breed')
).join(Breed, Dog.breed_id == Breed.id)
total = query.count()
dogs_query = query.offset((page - 1) * per_page).limit(per_page).all()
dogs_list: List[Dict[str, Any]] = [
{
'id': dog.id,
'name': dog.name,
'breed': dog.breed
}
for dog in dogs_query
]
return jsonify({
'dogs': dogs_list,
'page': page,
'per_page': per_page,
'total': total,
'total_pages': max(1, -(-total // per_page))
})
@app.route('/api/dogs/<int:id>', methods=['GET'])
def get_dog(id: int) -> tuple[Response, int] | Response:
# Query the specific dog by ID and join with breed to get breed name
dog_query = db.session.query(
Dog.id,
Dog.name,
Breed.name.label('breed'),
Dog.age,
Dog.description,
Dog.gender,
Dog.status
).join(Breed, Dog.breed_id == Breed.id).filter(Dog.id == id).first()
# Return 404 if dog not found
if not dog_query:
return jsonify({"error": "Dog not found"}), 404
# Convert the result to a dictionary
dog: Dict[str, Any] = {
'id': dog_query.id,
'name': dog_query.name,
'breed': dog_query.breed,
'age': dog_query.age,
'description': dog_query.description,
'gender': dog_query.gender,
'status': dog_query.status.name
}
return jsonify(dog)
## HERE
if __name__ == '__main__':
app.run(debug=True, port=5100) # Port 5100 to avoid macOS conflicts