Renamed to Spoolman
Spoolson just didn't sound that good after all
This commit is contained in:
0
spoolman/api/__init__.py
Normal file
0
spoolman/api/__init__.py
Normal file
0
spoolman/api/v1/__init__.py
Normal file
0
spoolman/api/v1/__init__.py
Normal file
111
spoolman/api/v1/filament.py
Normal file
111
spoolman/api/v1/filament.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""Filament related endpoints."""
|
||||
|
||||
from typing import Annotated, Optional, Union
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic.error_wrappers import ErrorWrapper
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from spoolman.api.v1.models import Filament, Message
|
||||
from spoolman.database import filament
|
||||
from spoolman.database.database import get_db_session
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/filament",
|
||||
tags=["filament"],
|
||||
)
|
||||
|
||||
# ruff: noqa: D103
|
||||
|
||||
|
||||
class FilamentParameters(BaseModel):
|
||||
name: Optional[str] = Field(
|
||||
max_length=64,
|
||||
description=(
|
||||
"Filament name, to distinguish this filament type among others from the same vendor."
|
||||
"Should contain its color for example."
|
||||
),
|
||||
)
|
||||
vendor_id: Optional[int] = Field(description="The ID of the vendor of this filament type.")
|
||||
material: Optional[str] = Field(max_length=64, description="The material of this filament, e.g. PLA.")
|
||||
price: Optional[float] = Field(ge=0, description="The price of this filament in the system configured currency.")
|
||||
density: float = Field(gt=0, description="The density of this filament in g/cm3.")
|
||||
diameter: float = Field(gt=0, description="The diameter of this filament in mm.")
|
||||
weight: Optional[float] = Field(gt=0, description="The weight of the filament in a full spool.")
|
||||
spool_weight: Optional[float] = Field(gt=0, description="The empty spool weight.")
|
||||
article_number: Optional[str] = Field(max_length=64, description="Vendor article number, e.g. EAN, QR code, etc.")
|
||||
comment: Optional[str] = Field(max_length=1024, description="Free text comment about this filament type.")
|
||||
|
||||
|
||||
class FilamentUpdateParameters(FilamentParameters):
|
||||
density: Optional[float] = Field(gt=0, description="The density of this filament in g/cm3.")
|
||||
diameter: Optional[float] = Field(gt=0, description="The diameter of this filament in mm.")
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def find(_vendor: Union[int, None] = None) -> list[Filament]:
|
||||
return []
|
||||
|
||||
|
||||
@router.get("/{filament_id}")
|
||||
async def get(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
filament_id: int,
|
||||
) -> Filament:
|
||||
db_item = await filament.get_by_id(db, filament_id)
|
||||
return Filament.from_db(db_item)
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def create(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
body: FilamentParameters,
|
||||
) -> Filament:
|
||||
db_item = await filament.create(
|
||||
db=db,
|
||||
density=body.density,
|
||||
diameter=body.diameter,
|
||||
name=body.name,
|
||||
vendor_id=body.vendor_id,
|
||||
material=body.material,
|
||||
price=body.price,
|
||||
weight=body.weight,
|
||||
spool_weight=body.spool_weight,
|
||||
article_number=body.article_number,
|
||||
comment=body.comment,
|
||||
)
|
||||
|
||||
return Filament.from_db(db_item)
|
||||
|
||||
|
||||
@router.patch("/{filament_id}")
|
||||
async def update(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
filament_id: int,
|
||||
body: FilamentUpdateParameters,
|
||||
) -> Filament:
|
||||
patch_data = body.dict(exclude_unset=True)
|
||||
|
||||
if "density" in patch_data and body.density is None:
|
||||
raise RequestValidationError([ErrorWrapper(ValueError("density cannot be unset"), ("query", "density"))])
|
||||
if "diameter" in patch_data and body.diameter is None:
|
||||
raise RequestValidationError([ErrorWrapper(ValueError("diameter cannot be unset"), ("query", "diameter"))])
|
||||
|
||||
db_item = await filament.update(
|
||||
db=db,
|
||||
filament_id=filament_id,
|
||||
data=patch_data,
|
||||
)
|
||||
|
||||
return Filament.from_db(db_item)
|
||||
|
||||
|
||||
@router.delete("/{filament_id}")
|
||||
async def delete(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
filament_id: int,
|
||||
) -> Message:
|
||||
await filament.delete(db, filament_id)
|
||||
return Message(message="Success!")
|
||||
91
spoolman/api/v1/models.py
Normal file
91
spoolman/api/v1/models.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""Pydantic data models for typing the FastAPI request/responses."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from spoolman.database import models
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
message: str = Field()
|
||||
|
||||
|
||||
class Vendor(BaseModel):
|
||||
id: int = Field(description="Unique internal ID of this vendor.")
|
||||
name: str = Field(max_length=64, description="Vendor name.")
|
||||
comment: Optional[str] = Field(max_length=1024, description="Free text comment about this vendor.")
|
||||
|
||||
@staticmethod
|
||||
def from_db(item: models.Vendor) -> "Vendor":
|
||||
"""Create a new Pydantic vendor object from a database vendor object."""
|
||||
return Vendor(
|
||||
id=item.id,
|
||||
name=item.name,
|
||||
comment=item.comment,
|
||||
)
|
||||
|
||||
|
||||
class Filament(BaseModel):
|
||||
id: int = Field(description="Unique internal ID of this filament type.")
|
||||
name: Optional[str] = Field(
|
||||
max_length=64,
|
||||
description=(
|
||||
"Filament name, to distinguish this filament type among others from the same vendor."
|
||||
"Should contain its color for example."
|
||||
),
|
||||
)
|
||||
vendor: Optional[Vendor] = Field(description="The vendor of this filament type.")
|
||||
material: Optional[str] = Field(max_length=64, description="The material of this filament, e.g. PLA.")
|
||||
price: Optional[float] = Field(ge=0, description="The price of this filament in the system configured currency.")
|
||||
density: float = Field(gt=0, description="The density of this filament in g/cm3.")
|
||||
diameter: float = Field(gt=0, description="The diameter of this filament in mm.")
|
||||
weight: Optional[float] = Field(gt=0, description="The weight of the filament in a full spool.")
|
||||
spool_weight: Optional[float] = Field(gt=0, description="The empty spool weight.")
|
||||
article_number: Optional[str] = Field(max_length=64, description="Vendor article number, e.g. EAN, QR code, etc.")
|
||||
comment: Optional[str] = Field(max_length=1024, description="Free text comment about this filament type.")
|
||||
|
||||
@staticmethod
|
||||
def from_db(item: models.Filament) -> "Filament":
|
||||
"""Create a new Pydantic filament object from a database filament object."""
|
||||
return Filament(
|
||||
id=item.id,
|
||||
name=item.name,
|
||||
vendor=Vendor.from_db(item.vendor) if item.vendor is not None else None,
|
||||
material=item.material,
|
||||
price=item.price,
|
||||
density=item.density,
|
||||
diameter=item.diameter,
|
||||
weight=item.weight,
|
||||
spool_weight=item.spool_weight,
|
||||
article_number=item.article_number,
|
||||
comment=item.comment,
|
||||
)
|
||||
|
||||
|
||||
class Spool(BaseModel):
|
||||
id: int = Field(description="Unique internal ID of this spool of filament.")
|
||||
registered: datetime = Field(description="When the spool was registered in the database.")
|
||||
first_used: Optional[datetime] = Field(description="First logged occurence of spool usage.")
|
||||
last_used: Optional[datetime] = Field(description="Last logged occurence of spool usage.")
|
||||
filament: Filament = Field(description="The filament type of this spool.")
|
||||
weight: float = Field(ge=0, description="Remaining weight of filament on the spool.")
|
||||
location: Optional[str] = Field(max_length=64, description="Where this spool can be found.")
|
||||
lot_nr: Optional[str] = Field(max_length=64, description="Vendor manufacturing lot/batch number of the spool.")
|
||||
comment: Optional[str] = Field(max_length=1024, description="Free text comment about this specific spool.")
|
||||
|
||||
@staticmethod
|
||||
def from_db(item: models.Spool) -> "Spool":
|
||||
"""Create a new Pydantic spool object from a database spool object."""
|
||||
return Spool(
|
||||
id=item.id,
|
||||
registered=item.registered,
|
||||
first_used=item.first_used,
|
||||
last_used=item.last_used,
|
||||
filament=Filament.from_db(item.filament),
|
||||
weight=item.weight,
|
||||
location=item.location,
|
||||
lot_nr=item.lot_nr,
|
||||
comment=item.comment,
|
||||
)
|
||||
32
spoolman/api/v1/router.py
Normal file
32
spoolman/api/v1/router.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""Router setup for the v1 version of the API."""
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
from spoolman.exceptions import ItemNotFoundError
|
||||
|
||||
from . import filament, models, spool, vendor
|
||||
|
||||
# ruff: noqa: D103
|
||||
|
||||
app = FastAPI(
|
||||
title="Spoolson REST API v1",
|
||||
version="1.0.0",
|
||||
root_path_in_servers=False,
|
||||
responses={404: {"model": models.Message}},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(ItemNotFoundError)
|
||||
async def itemnotfounderror_exception_handler(_request: Request, exc: ItemNotFoundError) -> Response:
|
||||
return JSONResponse(
|
||||
status_code=404,
|
||||
content={"message": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
app.include_router(filament.router)
|
||||
app.include_router(spool.router)
|
||||
app.include_router(vendor.router)
|
||||
155
spoolman/api/v1/spool.py
Normal file
155
spoolman/api/v1/spool.py
Normal file
@@ -0,0 +1,155 @@
|
||||
"""Spool related endpoints."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Optional, Union
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic.error_wrappers import ErrorWrapper
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from spoolman.api.v1.models import Message, Spool
|
||||
from spoolman.database import spool
|
||||
from spoolman.database.database import get_db_session
|
||||
from spoolman.exceptions import ItemCreateError
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/spool",
|
||||
tags=["spool"],
|
||||
)
|
||||
|
||||
# ruff: noqa: D103
|
||||
|
||||
|
||||
class SpoolParameters(BaseModel):
|
||||
first_used: Optional[datetime] = Field(description="First logged occurence of spool usage.")
|
||||
last_used: Optional[datetime] = Field(description="Last logged occurence of spool usage.")
|
||||
filament_id: int = Field(description="The ID of the filament type of this spool.")
|
||||
weight: Optional[float] = Field(
|
||||
ge=0,
|
||||
description=(
|
||||
"Remaining weight of filament on the spool. "
|
||||
"Leave empty to assume a full spool based on the weight parameters of the filament type."
|
||||
),
|
||||
)
|
||||
location: Optional[str] = Field(max_length=64, description="Where this spool can be found.")
|
||||
lot_nr: Optional[str] = Field(max_length=64, description="Vendor manufacturing lot/batch number of the spool.")
|
||||
comment: Optional[str] = Field(max_length=1024, description="Free text comment about this specific spool.")
|
||||
|
||||
|
||||
class SpoolUpdateParameters(SpoolParameters):
|
||||
filament_id: Optional[int] = Field(description="The ID of the filament type of this spool.")
|
||||
|
||||
|
||||
class SpoolUseParameters(BaseModel):
|
||||
use_length: Optional[float] = Field(description="Length of filament to reduce by, in mm.")
|
||||
use_weight: Optional[float] = Field(description="Filament weight to reduce by, in g.")
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def find(_filament: Union[int, None] = None) -> list[Spool]:
|
||||
return []
|
||||
|
||||
|
||||
@router.get("/{spool_id}")
|
||||
async def get(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
spool_id: int,
|
||||
) -> Spool:
|
||||
db_item = await spool.get_by_id(db, spool_id)
|
||||
return Spool.from_db(db_item)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/",
|
||||
response_model=Spool,
|
||||
responses={
|
||||
400: {"model": Message},
|
||||
},
|
||||
)
|
||||
async def create( # noqa: ANN201
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
body: SpoolParameters,
|
||||
):
|
||||
try:
|
||||
db_item = await spool.create(
|
||||
db=db,
|
||||
filament_id=body.filament_id,
|
||||
weight=body.weight,
|
||||
first_used=body.first_used,
|
||||
last_used=body.last_used,
|
||||
location=body.location,
|
||||
lot_nr=body.lot_nr,
|
||||
comment=body.comment,
|
||||
)
|
||||
return Spool.from_db(db_item)
|
||||
except ItemCreateError as exc:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/{spool_id}")
|
||||
async def update(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
spool_id: int,
|
||||
body: SpoolUpdateParameters,
|
||||
) -> Spool:
|
||||
patch_data = body.dict(exclude_unset=True)
|
||||
|
||||
if "filament_id" in patch_data and body.filament_id is None:
|
||||
raise RequestValidationError(
|
||||
[ErrorWrapper(ValueError("filament_id cannot be unset"), ("query", "filament_id"))],
|
||||
)
|
||||
|
||||
db_item = await spool.update(
|
||||
db=db,
|
||||
spool_id=spool_id,
|
||||
data=patch_data,
|
||||
)
|
||||
|
||||
return Spool.from_db(db_item)
|
||||
|
||||
|
||||
@router.delete("/{spool_id}")
|
||||
async def delete(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
spool_id: int,
|
||||
) -> Message:
|
||||
await spool.delete(db, spool_id)
|
||||
return Message(message="Success!")
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{spool_id}/use",
|
||||
response_model=Spool,
|
||||
responses={
|
||||
400: {"model": Message},
|
||||
},
|
||||
)
|
||||
async def use( # noqa: ANN201
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
spool_id: int,
|
||||
body: SpoolUseParameters,
|
||||
):
|
||||
if body.use_weight is not None and body.use_length is not None:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": "Only specify either use_weight or use_length."},
|
||||
)
|
||||
|
||||
if body.use_weight is not None:
|
||||
db_item = await spool.use_weight(db, spool_id, body.use_weight)
|
||||
return Spool.from_db(db_item)
|
||||
|
||||
if body.use_length is not None:
|
||||
db_item = await spool.use_length(db, spool_id, body.use_length)
|
||||
return Spool.from_db(db_item)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": "Either use_weight or use_length must be specified."},
|
||||
)
|
||||
87
spoolman/api/v1/vendor.py
Normal file
87
spoolman/api/v1/vendor.py
Normal file
@@ -0,0 +1,87 @@
|
||||
"""Vendor related endpoints."""
|
||||
|
||||
from typing import Annotated, Optional, Union
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic.error_wrappers import ErrorWrapper
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from spoolman.api.v1.models import Message, Vendor
|
||||
from spoolman.database import vendor
|
||||
from spoolman.database.database import get_db_session
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/vendor",
|
||||
tags=["vendor"],
|
||||
)
|
||||
|
||||
# ruff: noqa: D103
|
||||
|
||||
|
||||
class VendorParameters(BaseModel):
|
||||
name: str = Field(max_length=64, description="Vendor name.")
|
||||
comment: Optional[str] = Field(max_length=1024, description="Free text comment about this vendor.")
|
||||
|
||||
|
||||
class VendorUpdateParameters(VendorParameters):
|
||||
name: Optional[str] = Field(max_length=64, description="Vendor name.")
|
||||
comment: Optional[str] = Field(max_length=1024, description="Free text comment about this vendor.")
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def find(_name: Union[int, None] = None) -> list[Vendor]:
|
||||
return []
|
||||
|
||||
|
||||
@router.get("/{vendor_id}")
|
||||
async def get(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
vendor_id: int,
|
||||
) -> Vendor:
|
||||
db_item = await vendor.get_by_id(db, vendor_id)
|
||||
return Vendor.from_db(db_item)
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def create(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
body: VendorParameters,
|
||||
) -> Vendor:
|
||||
db_item = await vendor.create(
|
||||
db=db,
|
||||
name=body.name,
|
||||
comment=body.comment,
|
||||
)
|
||||
|
||||
return Vendor.from_db(db_item)
|
||||
|
||||
|
||||
@router.patch("/{vendor_id}")
|
||||
async def update(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
vendor_id: int,
|
||||
body: VendorUpdateParameters,
|
||||
) -> Vendor:
|
||||
patch_data = body.dict(exclude_unset=True)
|
||||
|
||||
if "name" in patch_data and body.name is None:
|
||||
raise RequestValidationError([ErrorWrapper(ValueError("name cannot be unset"), ("query", "name"))])
|
||||
|
||||
db_item = await vendor.update(
|
||||
db=db,
|
||||
vendor_id=vendor_id,
|
||||
data=patch_data,
|
||||
)
|
||||
|
||||
return Vendor.from_db(db_item)
|
||||
|
||||
|
||||
@router.delete("/{vendor_id}")
|
||||
async def delete(
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
vendor_id: int,
|
||||
) -> Message:
|
||||
await vendor.delete(db, vendor_id)
|
||||
return Message(message="Success!")
|
||||
Reference in New Issue
Block a user