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
41 changes: 39 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,51 @@
import requests
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)


def get_dog_image():
response = requests.get('https://dog.ceo/api/breeds/image/random')
if response.status_code == 200:
return response.json()['message']
return None


def get_cat_image():
response = requests.get('https://api.thecatapi.com/v1/images/search')
if response.status_code == 200:
return response.json()[0]['url']
return None

def get_photo_url(animal_type):
photo_functions = {
'dog': get_dog_image,
'cat': get_cat_image
}
get_photo = photo_functions.get(animal_type.lower())
return get_photo() if get_photo else None



@app.route('/')
def home() -> str:
return render_template('home.html')


@app.route('/health')
def health() -> tuple[str, int]:
return "", 200


@app.route('/animals', methods=['GET'])
def index() -> Response:
animals = Animal.query.all()
Expand All @@ -26,10 +55,14 @@ def index() -> Response:
@app.route('/animal', methods=['POST'])
def add_animal() -> tuple[Response, int]:
data = AnimalCreate(**request.get_json())
if not data.photo_url:
data.photo_url = get_photo_url(data.animal_type)
new_animal = Animal(
animal_type=data.animal_type,
name=data.name,
birth_date=data.birth_date
birth_date=data.birth_date,
breed=data.breed,
photo_url=data.photo_url,
)
db.session.add(new_animal)
db.session.commit()
Expand All @@ -48,9 +81,13 @@ def update_animal(pk: int) -> Union[Response, tuple[Response, int]]:
if not animal:
return jsonify({"message": "Animal not found"}), 404

if not data.photo_url:
data.photo_url = get_photo_url(data.animal_type)
animal.animal_type = data.animal_type
animal.name = data.name
animal.birth_date = data.birth_date
animal.breed = data.breed
animal.photo_url = data.photo_url
db.session.commit()
return jsonify(
{
Expand Down
34 changes: 34 additions & 0 deletions migrations/versions/f837bae0a5d9_commit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""comment

Revision ID: f837bae0a5d9
Revises: e08fc0218f8b
Create Date: 2024-04-18 21:34:33.851521

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'f837bae0a5d9'
down_revision = 'e08fc0218f8b'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('animal', schema=None) as batch_op:
batch_op.add_column(sa.Column('breed', sa.String(), nullable=False))
batch_op.add_column(sa.Column('photo_url', sa.String(), nullable=False))

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('animal', schema=None) as batch_op:
batch_op.drop_column('photo_url')
batch_op.drop_column('breed')

# ### end Alembic commands ###
13 changes: 11 additions & 2 deletions models/pydantic/models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from datetime import date
from pydantic import BaseModel, ConfigDict
from datetime import date, datetime, timedelta
from pydantic import BaseModel, ConfigDict, computed_field


class AnimalCreate(BaseModel):
animal_type: str
name: str
birth_date: date
breed: str
photo_url: str


class AnimalResponse(BaseModel):
Expand All @@ -15,3 +17,10 @@ class AnimalResponse(BaseModel):
animal_type: str
name: str
birth_date: date
breed: str
photo_url: str

@computed_field
@property
def age(self) -> int:
return date.today().year - self.birth_date.year
2 changes: 2 additions & 0 deletions models/sqlalchemy/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ 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)
photo_url = db.Column(db.String, nullable=False)
Loading