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
44 changes: 44 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# A generic, single database configuration.

[alembic]

# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url = driver://user:pass@localhost/dbname


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARNING
handlers = console
qualname =

[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
1 change: 1 addition & 0 deletions alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pyproject configuration, based on the generic configuration.
78 changes: 78 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = None

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.

This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.

Calls to context.execute() here emit the given string to the
script output.

"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online() -> None:
"""Run migrations in 'online' mode.

In this scenario we need to create an Engine
and associate a connection with the context.

"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
28 changes: 28 additions & 0 deletions alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}


def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}


def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
8 changes: 8 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
def home() -> str:
return render_template('home.html')

@app.route('/health', methods=['GET'])
def health() -> Response:
return jsonify(status='ok')


@app.route('/animals', methods=['GET'])
def index() -> Response:
Expand All @@ -28,7 +32,9 @@ def add_animal() -> tuple[Response, int]:
data = AnimalCreate(**request.get_json())
new_animal = Animal(
animal_type=data.animal_type,
breed=data.breed,
name=data.name,
photo=data.photo,
birth_date=data.birth_date
)
db.session.add(new_animal)
Expand All @@ -49,7 +55,9 @@ def update_animal(pk: int) -> Union[Response, tuple[Response, int]]:
return jsonify({"message": "Animal not found"}), 404

animal.animal_type = data.animal_type
animal.breed = data.breed
animal.name = data.name
animal.photo = data.photo
animal.birth_date = data.birth_date
db.session.commit()
return jsonify(
Expand Down
36 changes: 36 additions & 0 deletions migrations/versions/14c1ac011857_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""empty message

Revision ID: 14c1ac011857
Revises: e08fc0218f8b
Create Date: 2025-06-09 13:20:38.565371

"""
from alembic import op
import sqlalchemy as sa


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


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('animal',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('animal_type', sa.String(), nullable=False),
sa.Column('breed', sa.String(), nullable=False),
sa.Column('photo', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('birth_date', sa.Date(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('animal')
# ### end Alembic commands ###
22 changes: 21 additions & 1 deletion models/pydantic/models.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,37 @@
from datetime import date
from pydantic import BaseModel, ConfigDict
from pydantic import BaseModel, ConfigDict, field_validator, HttpUrl, computed_field


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

@field_validator("birth_date")
@classmethod
def validate_birth_date(cls, v: date) -> date:
if v > date.today():
raise ValueError("Birth date cannot be in the future")
return v


class AnimalResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)

id: int
animal_type: str
breed: str
name: str
photo: str
birth_date: date

@computed_field(return_type=int)
@property
def age(self) -> int:
today = date.today()
age = today.year - self.birth_date.year
if (today.month, today.day) < (self.birth_date.month, self.birth_date.day):
age -= 1
return age
2 changes: 2 additions & 0 deletions models/sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@
class Animal(db.Model):
id = db.Column(db.Integer, primary_key=True)
animal_type = db.Column(db.String, nullable=False)
breed = db.Column(db.String, nullable=False)
photo = db.Column(db.String, nullable=False)
name = db.Column(db.String, nullable=False)
birth_date = db.Column(db.Date, nullable=False)
2 changes: 2 additions & 0 deletions models/sqlalchemy/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ class Animal(db.Model):

id = db.Column(db.Integer, primary_key=True)
animal_type = db.Column(db.String, nullable=False)
breed = db.Column(db.String, nullable=False)
photo = db.Column(db.String, nullable=False)
name = db.Column(db.String, nullable=False)
birth_date = db.Column(db.Date, nullable=False)
Loading