forked from rusalforever/course_flask
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
94 lines (72 loc) · 2.59 KB
/
app.py
File metadata and controls
94 lines (72 loc) · 2.59 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
84
85
86
87
88
89
90
91
92
93
94
from flask import Flask, jsonify, request, Response, render_template
from models.pydantic.models import AnimalCreate, AnimalResponse
from typing import Union
from settings import settings
from database import init_db
from models.sqlalchemy.models import Animal
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = settings.sqlalchemy_database_uri
db = init_db(app)
@app.route('/')
def home() -> str:
return render_template('home.html')
@app.route('/animals', methods=['GET'])
def index() -> Response:
animals = Animal.query.all()
return jsonify({"animals": [AnimalResponse.model_validate(animal).model_dump(mode='json') for animal in animals]})
@app.route('/animal', methods=['POST'])
def add_animal() -> tuple[Response, int]:
data = AnimalCreate(**request.get_json())
new_animal = Animal(
animal_type=data.animal_type,
name=data.name,
birth_date=data.birth_date
)
db.session.add(new_animal)
db.session.commit()
return jsonify(
{
"message": "Animal added successfully!",
"animal": AnimalResponse.model_validate(new_animal).model_dump(mode='json')
}
), 201
@app.route('/animal/<int:pk>', methods=['PUT'])
def update_animal(pk: int) -> Union[Response, tuple[Response, int]]:
data = AnimalCreate(**request.get_json())
animal = Animal.query.get(pk)
if not animal:
return jsonify({"message": "Animal not found"}), 404
animal.animal_type = data.animal_type
animal.name = data.name
animal.birth_date = data.birth_date
db.session.commit()
return jsonify(
{
"message": "Animal updated successfully!",
"animal": AnimalResponse.model_validate(animal).model_dump(mode='json'),
},
)
@app.route('/animal/<int:pk>', methods=['GET'])
def retrieve_animal(pk: int) -> Union[Response, tuple[Response, int]]:
animal = Animal.query.get(pk)
if not animal:
return jsonify({"message": "Animal not found"}), 404
return jsonify(
{
"animal": AnimalResponse.model_validate(animal).model_dump(mode='json'),
}
)
@app.route('/animal/<int:pk>', methods=['DELETE'])
def delete_animal(pk: int) -> Union[Response, tuple[Response, int]]:
animal = Animal.query.get(pk)
if not animal:
return jsonify({"message": "Animal not found"}), 404
db.session.delete(animal)
db.session.commit()
return jsonify({"message": "Animal deleted successfully!"})
def initialize_app():
with app.app_context():
db.create_all()
if __name__ == '__main__':
initialize_app()
app.run(debug=True)