Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from flask import Flask, jsonify, request, Response, render_template
from flask import Flask, jsonify, request, Response, render_template, make_response

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
from datetime import datetime


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = settings.sqlalchemy_database_uri
Expand All @@ -23,13 +25,27 @@ def index() -> Response:
return jsonify({"animals": [AnimalResponse.model_validate(animal).model_dump(mode='json') for animal in animals]})


@app.route('/health', methods=['GET'])
def get_health() -> Response:
response = make_response("Hi")
response.status_code = 200
return response


@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
birth_date=data.birth_date,
breed=data.breed,
foto=data.foto,
age=data.age



)
db.session.add(new_animal)
db.session.commit()
Expand All @@ -51,6 +67,9 @@ def update_animal(pk: int) -> Union[Response, tuple[Response, int]]:
animal.animal_type = data.animal_type
animal.name = data.name
animal.birth_date = data.birth_date
animal.foto = data.foto
animal.breed = data.breed
animal.age = data.age
db.session.commit()
return jsonify(
{
Expand Down Expand Up @@ -91,4 +110,4 @@ def initialize_app():

if __name__ == '__main__':
initialize_app()
app.run(debug=True)
app.run(debug=True, port=8000)
8 changes: 7 additions & 1 deletion models/pydantic/models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from datetime import date
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict


class AnimalCreate(BaseModel):
animal_type: str
name: str
birth_date: date
breed: str
foto: str
age: int


class AnimalResponse(BaseModel):
Expand All @@ -15,3 +18,6 @@ class AnimalResponse(BaseModel):
animal_type: str
name: str
birth_date: date
breed: str
foto: str
age: int
3 changes: 3 additions & 0 deletions models/sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ class Animal(db.Model):
animal_type = db.Column(db.String, nullable=False)
name = db.Column(db.String, nullable=False)
birth_date = db.Column(db.Date, nullable=False)
breed = db.Column(db.String, nullable=False)
foto = db.Column(db.String, nullable=False)
age = db.Column(db.Integer, nullable=False)
4 changes: 4 additions & 0 deletions models/sqlalchemy/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ class Animal(db.Model):
animal_type = db.Column(db.String, nullable=False)
name = db.Column(db.String, nullable=False)
birth_date = db.Column(db.Date, nullable=False)
breed = db.Column(db.String, nullable=False)
foto = db.Column(db.String, nullable=False)
age = db.Column(db.Integer, nullable=False)

199 changes: 115 additions & 84 deletions templates/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ <h2>Animals in the Shelter</h2>
<label for="birth_date">Birth Date:</label>
<input type="date" class="form-control" id="birth_date" required>
</div>
<div class="form-group">
<label for="breed">Breed:</label>
<input type="text" class="form-control" id="breed" required>
</div>
<div class="form-group">
<label for="foto">FOTO:</label>
<input type="text" class="form-control" id="foto" required>
<button type="submit" class="btn btn-primary">Add Animal</button>
</form>
</div>
Expand All @@ -46,6 +53,9 @@ <h4 class="mt-4">List of animals:</h4>
<th>Animal Type</th>
<th>Name</th>
<th>Birth Date</th>
<th>Age</th>
<th>Breed</th>
<th>Foto</th>
<th>Actions</th>
</tr>
</thead>
Expand Down Expand Up @@ -80,6 +90,14 @@ <h5 class="modal-title">Edit Animal</h5>
<label for="editAnimalBirthDate">Birth Date:</label>
<input type="date" class="form-control" id="editAnimalBirthDate" required>
</div>
<div class="form-group">
<label for="editAnimalBreed">Breed:</label>
<input type="text" class="form-control" id="editAnimalBreed" required>
</div>
<div class="form-group">
<label for="editAnimalFoto">Foto:</label>
<input type="text" class="form-control" id="editAnimalFoto" required>
</div>
</form>
</div>
<div class="modal-footer">
Expand All @@ -91,99 +109,112 @@ <h5 class="modal-title">Edit Animal</h5>
</div>

<script>
// Update animal
function updateAnimal(id) {
// Fetch the current details of the animal to pre-populate the form.
// This assumes you have a backend route to get details of a single animal.
$.getJSON(`/animal/${id}`, function(data) {
$('#editAnimalId').val(data.animal.id);
$('#editAnimalType').val(data.animal.animal_type);
$('#editAnimalName').val(data.animal.name);
$('#editAnimalBirthDate').val(data.animal.birth_date);
$('#editAnimalModal').modal('show');
});
}

function submitEditAnimal() {
const updatedAnimal = {
animal_type: $('#editAnimalType').val(),
name: $('#editAnimalName').val(),
birth_date: $('#editAnimalBirthDate').val()
};

const animalId = $('#editAnimalId').val();

$.ajax({
url: `/animal/${animalId}`,
type: 'PUT',
data: JSON.stringify(updatedAnimal),
contentType: 'application/json',
success: function() {
$('#editAnimalModal').modal('hide');
fetchAnimals();
}
});
}


// Fetch all animals and display them
function fetchAnimals() {
$.getJSON('/animals', function(data) {
$('#animalsList').empty();
data.animals.forEach(animal => {
console.log(animal)
$('#animalsList').append(`
<tr>
<td>${animal.animal_type}</td>
<td>${animal.name}</td>
<td>${animal.birth_date}</td>
<td>
<button class="btn btn-warning btn-sm" onclick="updateAnimal(${animal.id})">Update</button>
<button class="btn btn-danger btn-sm" onclick="deleteAnimal(${animal.id})">Delete</button>
</td>
</tr>
`);
});
// Update animal
function updateAnimal(id) {
$.getJSON(`/animal/${id}`, function(data) {
$('#editAnimalId').val(data.animal.id);
$('#editAnimalType').val(data.animal.animal_type);
$('#editAnimalName').val(data.animal.name);
$('#editAnimalBirthDate').val(data.animal.birth_date);
$('#editAnimalBreed').val(data.animal.breed);
$('#editAnimalFoto').val(data.animal.foto);

const birthDate = new Date(data.animal.birth_date);
const ageInMilliseconds = Date.now() - birthDate.getTime();
const ageInYears = new Date(ageInMilliseconds).getUTCFullYear() - 1970;

$('#editAnimalAge').val(ageInYears);
$('#editAnimalModal').modal('show');
});
}
function submitEditAnimal() {
const updatedAnimal = {
id: $('#editAnimalId').val(),
animal_type: $('#editAnimalType').val(),
name: $('#editAnimalName').val(),
birth_date: $('#editAnimalBirthDate').val(),
breed: document.getElementById('editAnimalBreed').value,
foto: $('#editAnimalFoto').val() // Include the foto field
};
const birthDate = new Date($('#editAnimalBirthDate').val());
const ageInMilliseconds = Date.now() - birthDate.getTime();
const ageInYears = new Date(ageInMilliseconds).getUTCFullYear() - 1970;
updatedAnimal.age = ageInYears;

$.ajax({
url: `/animal/${updatedAnimal.id}`,
type: 'PUT',
data: JSON.stringify(updatedAnimal),
contentType: 'application/json',
success: function() {
$('#editAnimalModal').modal('hide');
fetchAnimals();
}
});
}

// Add new animal
$('#addAnimalForm').on('submit', function(e) {
e.preventDefault();
const birthDate = new Date($('#birth_date').val());
const ageInMilliseconds = Date.now() - birthDate.getTime();
const ageInYears = new Date(ageInMilliseconds).getUTCFullYear() - 1970;

const newAnimal = {
animal_type: $('#animal_type').val(),
name: $('#name').val(),
birth_date: $('#birth_date').val(),
breed: $('#breed').val(),
foto: $('#foto').val(),
age: ageInYears // Set the age
};
$.ajax({
url: '/animal',
type: 'POST',
data: JSON.stringify(newAnimal),
contentType: 'application/json',
success: function() {
fetchAnimals();
$('#addAnimalForm')[0].reset();
}
});
});

function fetchAnimals() {
$.getJSON('/animals', function(data) {
$('#animalsList').empty();
data.animals.forEach(animal => {
$('#animalsList').append(`
<tr>
<td>${animal.animal_type}</td>
<td>${animal.name}</td>
<td>${animal.birth_date}</td>
<td>${animal.age}</td>
<td>
<button class="btn btn-warning btn-sm" onclick="updateAnimal(${animal.id})">Update</button>
<button class="btn btn-danger btn-sm" onclick="deleteAnimal(${animal.id})">Delete</button>
</td>
</tr>
`);
});
}
});
}

// Add new animal
$('#addAnimalForm').on('submit', function(e) {
e.preventDefault();
const newAnimal = {
animal_type: $('#animal_type').val(),
name: $('#name').val(),
birth_date: $('#birth_date').val()
};
// Delete animal
function deleteAnimal(id) {
if (confirm('Are you sure you want to delete this animal?')) {
$.ajax({
url: '/animal',
type: 'POST',
data: JSON.stringify(newAnimal),
contentType: 'application/json',
url: `/animal/${id}`,
type: 'DELETE',
success: function() {
fetchAnimals();
$('#addAnimalForm')[0].reset();
}
});
});

// Delete animal
function deleteAnimal(id) {
if (confirm('Are you sure you want to delete this animal?')) {
$.ajax({
url: `/animal/${id}`,
type: 'DELETE',
success: function() {
fetchAnimals();
}
});
}
}
}

// Initial fetch
fetchAnimals();


// Initial fetch
fetchAnimals();
</script>
</body>
</html>