Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ venv/
.pytest_cache/
.ruff_cache/
*.egg-info/
.coverage
htmlcov/
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.9
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@ API REST para gestión de gastos personales. Proyecto de portfolio con foco en *
python -m venv .venv
source .venv/bin/activate
pip install -r requirements-dev.txt
pre-commit install
alembic upgrade head
uvicorn app.main:app --reload
```

`pre-commit install` deja `ruff check --fix` y `ruff format` corriendo antes de cada commit, así un fallo de lint se detecta en tu máquina y no en el CI.

Docs interactivas en `http://localhost:8000/docs`.

## Migraciones (Alembic)
Expand Down
4 changes: 1 addition & 3 deletions alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ def run_migrations_online() -> None:
)

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

with context.begin_transaction():
context.run_migrations()
Expand Down
73 changes: 43 additions & 30 deletions alembic/versions/896f574a4c93_create_initial_schema.py
Original file line number Diff line number Diff line change
@@ -1,59 +1,72 @@
"""create initial schema

Revision ID: 896f574a4c93
Revises:
Revises:
Create Date: 2026-08-12 09:28:21.452383

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '896f574a4c93'
revision: str = "896f574a4c93"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(length=255), nullable=False),
sa.Column('hashed_password', sa.String(length=255), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
op.create_table(
"users",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("email", sa.String(length=255), nullable=False),
sa.Column("hashed_password", sa.String(length=255), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_table('categories',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True)
op.create_table(
"categories",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.String(length=100), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table('expenses',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('amount', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('description', sa.String(length=255), nullable=False),
sa.Column('date', sa.Date(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('category_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
op.create_table(
"expenses",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("amount", sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column("description", sa.String(length=255), nullable=False),
sa.Column("date", sa.Date(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("category_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["category_id"],
["categories.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('expenses')
op.drop_table('categories')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
op.drop_table("expenses")
op.drop_table("categories")
op.drop_index(op.f("ix_users_email"), table_name="users")
op.drop_table("users")
# ### end Alembic commands ###
8 changes: 6 additions & 2 deletions app/api/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
def register(user_in: UserCreate, db: Session = Depends(get_db)) -> User:
existing = db.query(User).filter(User.email == user_in.email).first()
if existing:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered"
)

user = User(email=user_in.email, hashed_password=hash_password(user_in.password))
db.add(user)
Expand All @@ -28,7 +30,9 @@ def register(user_in: UserCreate, db: Session = Depends(get_db)) -> User:
@router.post("/login", response_model=Token)
@limiter.limit("5/minute")
def login(
request: Request, form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)
request: Request,
form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db),
) -> Token:
user = db.query(User).filter(User.email == form_data.username).first()
if not user or not verify_password(form_data.password, user.hashed_password):
Expand Down
8 changes: 6 additions & 2 deletions app/core/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,18 @@ def verify_password(plain_password: str, hashed_password: str) -> bool:


def create_access_token(subject: str) -> str:
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
expire = datetime.now(timezone.utc) + timedelta(
minutes=settings.access_token_expire_minutes
)
payload = {"sub": subject, "exp": expire}
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)


def decode_access_token(token: str) -> Optional[str]:
try:
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
payload = jwt.decode(
token, settings.secret_key, algorithms=[settings.algorithm]
)
return payload.get("sub")
except JWTError:
return None
4 changes: 3 additions & 1 deletion app/db/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

from app.core.config import settings

connect_args = {"check_same_thread": False} if settings.database_url.startswith("sqlite") else {}
connect_args = (
{"check_same_thread": False} if settings.database_url.startswith("sqlite") else {}
)

engine = create_engine(settings.database_url, connect_args=connect_args)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Expand Down
8 changes: 6 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,13 @@ def http_exception_handler(request, exc: StarletteHTTPException) -> JSONResponse

@app.exception_handler(RequestValidationError)
def validation_exception_handler(request, exc: RequestValidationError) -> JSONResponse:
return JSONResponse(status_code=422, content={"error": "Validation failed", "details": exc.errors()})
return JSONResponse(
status_code=422, content={"error": "Validation failed", "details": exc.errors()}
)


@app.exception_handler(RateLimitExceeded)
def rate_limit_exceeded_handler(request, exc: RateLimitExceeded) -> JSONResponse:
return JSONResponse(status_code=429, content={"error": f"Rate limit exceeded: {exc.detail}"})
return JSONResponse(
status_code=429, content={"error": f"Rate limit exceeded: {exc.detail}"}
)
8 changes: 6 additions & 2 deletions app/models/expense.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@ class Expense(Base):
amount: Mapped[float] = mapped_column(Numeric(10, 2), nullable=False)
description: Mapped[str] = mapped_column(String(255), nullable=False)
date: Mapped[date_] = mapped_column(Date, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc))
created_at: Mapped[datetime] = mapped_column(
DateTime, default=lambda: datetime.now(timezone.utc)
)

user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), nullable=False)
category_id: Mapped[int] = mapped_column(
ForeignKey("categories.id"), nullable=False
)

owner: Mapped["User"] = relationship(back_populates="expenses")
category: Mapped["Category"] = relationship(back_populates="expenses")
16 changes: 12 additions & 4 deletions app/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,17 @@ class User(Base):
__tablename__ = "users"

id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
email: Mapped[str] = mapped_column(
String(255), unique=True, index=True, nullable=False
)
hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc))
created_at: Mapped[datetime] = mapped_column(
DateTime, default=lambda: datetime.now(timezone.utc)
)

categories: Mapped[list["Category"]] = relationship(back_populates="owner", cascade="all, delete-orphan")
expenses: Mapped[list["Expense"]] = relationship(back_populates="owner", cascade="all, delete-orphan")
categories: Mapped[list["Category"]] = relationship(
back_populates="owner", cascade="all, delete-orphan"
)
expenses: Mapped[list["Expense"]] = relationship(
back_populates="owner", cascade="all, delete-orphan"
)
16 changes: 12 additions & 4 deletions app/services/category_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
from app.schemas.category import CategoryCreate, CategoryUpdate


def list_categories(db: Session, user_id: int, skip: int = 0, limit: int = 50) -> list[Category]:
def list_categories(
db: Session, user_id: int, skip: int = 0, limit: int = 50
) -> list[Category]:
return (
db.query(Category)
.filter(Category.user_id == user_id)
Expand All @@ -26,14 +28,20 @@ def create_category(db: Session, user_id: int, data: CategoryCreate) -> Category

def get_category_or_404(db: Session, user_id: int, category_id: int) -> Category:
category = (
db.query(Category).filter(Category.id == category_id, Category.user_id == user_id).first()
db.query(Category)
.filter(Category.id == category_id, Category.user_id == user_id)
.first()
)
if category is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Category not found"
)
return category


def update_category(db: Session, user_id: int, category_id: int, data: CategoryUpdate) -> Category:
def update_category(
db: Session, user_id: int, category_id: int, data: CategoryUpdate
) -> Category:
category = get_category_or_404(db, user_id, category_id)
if data.name is not None:
category.name = data.name
Expand Down
18 changes: 14 additions & 4 deletions app/services/expense_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
from app.services.category_service import get_category_or_404


def list_expenses(db: Session, user_id: int, skip: int = 0, limit: int = 50) -> list[Expense]:
def list_expenses(
db: Session, user_id: int, skip: int = 0, limit: int = 50
) -> list[Expense]:
return (
db.query(Expense)
.filter(Expense.user_id == user_id)
Expand All @@ -33,13 +35,21 @@ def create_expense(db: Session, user_id: int, data: ExpenseCreate) -> Expense:


def get_expense_or_404(db: Session, user_id: int, expense_id: int) -> Expense:
expense = db.query(Expense).filter(Expense.id == expense_id, Expense.user_id == user_id).first()
expense = (
db.query(Expense)
.filter(Expense.id == expense_id, Expense.user_id == user_id)
.first()
)
if expense is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Expense not found")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Expense not found"
)
return expense


def update_expense(db: Session, user_id: int, expense_id: int, data: ExpenseUpdate) -> Expense:
def update_expense(
db: Session, user_id: int, expense_id: int, data: ExpenseUpdate
) -> Expense:
expense = get_expense_or_404(db, user_id, expense_id)
if data.category_id is not None:
get_category_or_404(db, user_id, data.category_id)
Expand Down
1 change: 1 addition & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ pytest==8.3.3
pytest-cov==5.0.0
httpx==0.27.2
ruff==0.6.9
pre-commit==4.3.0
4 changes: 3 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def override_get_db():

@pytest.fixture()
def auth_headers(client):
client.post("/auth/register", json={"email": "test@example.com", "password": "secret123"})
client.post(
"/auth/register", json={"email": "test@example.com", "password": "secret123"}
)
response = client.post(
"/auth/login",
data={"username": "test@example.com", "password": "secret123"},
Expand Down
16 changes: 12 additions & 4 deletions tests/integration/test_auth.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
def test_register_and_login(client):
response = client.post("/auth/register", json={"email": "a@example.com", "password": "secret123"})
response = client.post(
"/auth/register", json={"email": "a@example.com", "password": "secret123"}
)
assert response.status_code == 201
assert response.json()["email"] == "a@example.com"

Expand All @@ -11,13 +13,19 @@ def test_register_and_login(client):


def test_register_duplicate_email_fails(client):
client.post("/auth/register", json={"email": "dup@example.com", "password": "secret123"})
response = client.post("/auth/register", json={"email": "dup@example.com", "password": "secret123"})
client.post(
"/auth/register", json={"email": "dup@example.com", "password": "secret123"}
)
response = client.post(
"/auth/register", json={"email": "dup@example.com", "password": "secret123"}
)
assert response.status_code == 400


def test_login_wrong_password_fails(client):
client.post("/auth/register", json={"email": "b@example.com", "password": "secret123"})
client.post(
"/auth/register", json={"email": "b@example.com", "password": "secret123"}
)
response = client.post(
"/auth/login", data={"username": "b@example.com", "password": "wrong"}
)
Expand Down
Loading
Loading