Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(proofs): improve schema and add validation for create & update #349

Closed
wants to merge 3 commits into from
Closed
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
12 changes: 8 additions & 4 deletions app/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
ProductCreate,
ProductFilter,
ProductFull,
ProofCreate,
ProofCreateWithValidation,
ProofFilter,
ProofUpdate,
ProofUpdateWithValidation,
UserCreate,
)
from app.utils import fetch_location_openstreetmap_details
Expand Down Expand Up @@ -379,7 +379,9 @@ def get_proof_by_id(db: Session, id: int) -> Proof | None:
return db.query(Proof).filter(Proof.id == id).first()


def create_proof(db: Session, proof: ProofCreate, user: UserCreate, source: str = None):
def create_proof(
db: Session, proof: ProofCreateWithValidation, user: UserCreate, source: str = None
):
db_proof = Proof(**proof.model_dump(), owner=user.user_id, source=source)
db.add(db_proof)
db.commit()
Expand Down Expand Up @@ -464,7 +466,9 @@ def set_proof_location(db: Session, proof: Proof, location: Location) -> Proof:
return proof


def update_proof(db: Session, proof: Proof, new_values: ProofUpdate) -> Proof:
def update_proof(
db: Session, proof: Proof, new_values: ProofUpdateWithValidation
) -> Proof:
new_values_cleaned = new_values.model_dump(exclude_unset=True)
for key in new_values_cleaned:
setattr(proof, key, new_values_cleaned[key])
Expand Down
26 changes: 5 additions & 21 deletions app/routers/proofs.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
from typing import Annotated, Optional

from fastapi import (
APIRouter,
BackgroundTasks,
Depends,
Form,
HTTPException,
UploadFile,
status,
Expand All @@ -18,7 +15,6 @@
from app import crud, schemas, tasks
from app.auth import get_current_user
from app.db import get_db
from app.enums import CurrencyEnum, LocationOSMEnum, ProofTypeEnum
from app.models import Proof

router = APIRouter(prefix="/proofs")
Expand Down Expand Up @@ -46,16 +42,10 @@ def get_user_proofs(
)
def upload_proof(
file: UploadFile,
type: Annotated[ProofTypeEnum, Form(description="The type of the proof")],
background_tasks: BackgroundTasks,
location_osm_id: Optional[str] = Form(
description="Proof location OSM id", default=None
),
location_osm_type: Optional[LocationOSMEnum] = Form(
description="Proof location OSM type", default=None
proof_partial: schemas.ProofBaseWithValidation = Depends(
schemas.ProofBaseWithValidation
),
date: Optional[str] = Form(description="Proof date", default=None),
currency: Optional[CurrencyEnum] = Form(description="Proof currency", default=None),
app_name: str | None = None,
current_user: schemas.UserCreate = Depends(get_current_user),
db: Session = Depends(get_db),
Expand All @@ -69,14 +59,8 @@ def upload_proof(
This endpoint requires authentication.
"""
file_path, mimetype = crud.create_proof_file(file)
proof = schemas.ProofCreate(
file_path=file_path,
mimetype=mimetype,
type=type,
location_osm_id=location_osm_id,
location_osm_type=location_osm_type,
date=date,
currency=currency,
proof = schemas.ProofCreateWithValidation(
file_path=file_path, mimetype=mimetype, **proof_partial.model_dump()
)
# create proof
db_proof = crud.create_proof(
Expand Down Expand Up @@ -125,7 +109,7 @@ def get_user_proof_by_id(
)
def update_proof(
proof_id: int,
proof_new_values: schemas.ProofUpdate,
proof_new_values: schemas.ProofUpdateWithValidation,
current_user: schemas.UserCreate = Depends(get_current_user),
db: Session = Depends(get_db),
) -> Proof:
Expand Down
89 changes: 74 additions & 15 deletions app/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from copy import deepcopy
from typing import Any, Optional, Tuple, Type

from fastapi import Form
from fastapi_filter.contrib.sqlalchemy import Filter
from openfoodfacts import Flavor
from openfoodfacts.taxonomy import get_taxonomy
Expand Down Expand Up @@ -45,6 +46,19 @@ def make_field_optional(
)


def form_body(cls):
"""
https://stackoverflow.com/a/65547551/4293684
"""
cls.__signature__ = cls.__signature__.replace(
parameters=[
arg.replace(default=Form(...))
for arg in cls.__signature__.parameters.values()
]
)
return cls


# Session
# ------------------------------------------------------------------------------
class SessionBase(BaseModel):
Expand Down Expand Up @@ -202,46 +216,91 @@ class LocationFull(LocationCreate):


# Proof
# ProofBase > ProofBaseWithValidation & ProofCreate > ProofCreateWithValidation
# ProofBase > ProofBaseWithValidation > ProofUpdateWithValidation
# ProofBase > ProofCreate > ProofFull > ProofFullWithRelations
# ProofBase > ProofUpdate
# ------------------------------------------------------------------------------
class ProofBase(BaseModel):
model_config = ConfigDict(
from_attributes=True, arbitrary_types_allowed=True, extra="forbid"
)

type: ProofTypeEnum | None = None
location_osm_id: int | None = Field(
gt=0,
description="ID of the location in OpenStreetMap: the store where the product was bought.",
examples=[1234567890],
)
location_osm_type: LocationOSMEnum | None = Field(
description="type of the OpenStreetMap location object. Stores can be represented as nodes, "
"ways or relations in OpenStreetMap. It is necessary to be able to fetch the correct "
"information about the store using the ID.",
examples=["NODE", "WAY", "RELATION"],
)
currency: CurrencyEnum | None = Field(
description="currency of the price, as a string. "
"The currency must be a valid currency code. "
"See https://en.wikipedia.org/wiki/ISO_4217 for a list of valid currency codes.",
"See https://en.wikipedia.org/wiki/ISO_4217 for a list of valid currency codes. "
"Must be set if type is PRICE_TAG or RECEIPT.",
examples=["EUR", "USD"],
)
date: datetime.date | None = Field(
description="date of the proof.", examples=["2024-01-01"]
description="date of the proof. Must be set if type is PRICE_TAG or RECEIPT.",
examples=["2024-01-01"],
)


@form_body
class ProofBaseWithValidation(ProofBase):
"""A version of `ProofBase` with validations.
These validations are not done in the `ProofFull` model
because they are time-consuming and only necessary when creating or
updating a price from the API.
"""

pass


class ProofCreate(ProofBase):
# file_path is str | null because we can mask the file path in the response
# if the proof is not public
file_path: str | None
mimetype: str
location_osm_id: int | None = Field(
gt=0,
description="ID of the location in OpenStreetMap: the store where the product was bought.",
examples=[1234567890],
)
location_osm_type: LocationOSMEnum | None = Field(
description="type of the OpenStreetMap location object. Stores can be represented as nodes, "
"ways or relations in OpenStreetMap. It is necessary to be able to fetch the correct "
"information about the store using the ID.",
examples=["NODE", "WAY", "RELATION"],
)


class ProofCreateWithValidation(ProofBaseWithValidation, ProofCreate):
@model_validator(mode="after")
def location_is_mandatory(self): # type: ignore
if self.type in [ProofTypeEnum.PRICE_TAG, ProofTypeEnum.RECEIPT]:
if not self.location_osm_id:
raise ValueError(
"`location_osm_id` must be set if `type` is PRICE_TAG or RECEIPT"
)
elif not self.location_osm_type:
raise ValueError(
"`location_osm_type` must be set if `type` is PRICE_TAG or RECEIPT"
)
return self

@model_validator(mode="after")
def currency_is_mandatory(self): # type: ignore
if self.type in [ProofTypeEnum.PRICE_TAG, ProofTypeEnum.RECEIPT]:
if not self.date:
raise ValueError(
"`currency` must be set if `type` is PRICE_TAG or RECEIPT"
)
return self

@model_validator(mode="after")
def date_is_mandatory(self): # type: ignore
if self.type in [ProofTypeEnum.PRICE_TAG, ProofTypeEnum.RECEIPT]:
if not self.date:
raise ValueError("`date` must be set if `type` is PRICE_TAG or RECEIPT")
return self


@partial_model
class ProofUpdate(ProofBase):
class ProofUpdateWithValidation(ProofBaseWithValidation):
pass


Expand Down
Loading
Loading