Added support for color_hex alpha channel

This commit is contained in:
Donkie
2023-08-12 21:32:20 +02:00
parent 6934748b14
commit 4cb2542a41
6 changed files with 69 additions and 8 deletions

View File

@@ -2,6 +2,6 @@
Creating a new version: Creating a new version:
```bash ```bash
python -m spoolman.main pdm run python -m spoolman.main
pdm run alembic revision -m "some title" --autogenerate pdm run alembic revision -m "some title" --autogenerate
``` ```

View File

@@ -0,0 +1,24 @@
"""color_hex alpha.
Revision ID: 92793c8a937c
Revises: 92186a5f7b0f
Create Date: 2023-08-12 21:21:08.536216
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "92793c8a937c"
down_revision = "92186a5f7b0f"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""Perform the upgrade."""
op.alter_column("filament", "color_hex", type_=sa.String(length=8), existing_nullable=True)
def downgrade() -> None:
"""Perform the downgrade."""
op.alter_column("filament", "color_hex", type_=sa.String(length=6), existing_nullable=True)

View File

@@ -6,7 +6,7 @@ from typing import Annotated, Optional
from fastapi import APIRouter, Depends, Query from fastapi import APIRouter, Depends, Query
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field from pydantic import BaseModel, Field, validator
from pydantic.error_wrappers import ErrorWrapper from pydantic.error_wrappers import ErrorWrapper
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
@@ -74,12 +74,29 @@ class FilamentParameters(BaseModel):
example=60, example=60,
) )
color_hex: Optional[str] = Field( color_hex: Optional[str] = Field(
min_length=6, description="Hexadecimal color code of the filament, e.g. FF0000 for red. Supports alpha channel at the end.",
max_length=6,
description="Hexadecimal color code of the filament, e.g. FF0000 for red. (no leading #)",
example="FF0000", example="FF0000",
) )
@validator("color_hex")
@classmethod
def color_hex_validator(cls, v: Optional[str]) -> Optional[str]: # noqa: ANN102
"""Validate the color_hex field."""
if not v:
return None
if v.startswith("#"):
v = v[1:]
v = v.upper()
for c in v:
if c not in "0123456789ABCDEF":
raise ValueError("Invalid character in color code.")
if len(v) not in (6, 8):
raise ValueError("Color code must be 6 or 8 characters long.")
return v
class FilamentUpdateParameters(FilamentParameters): class FilamentUpdateParameters(FilamentParameters):
density: Optional[float] = Field(gt=0, description="The density of this filament in g/cm3.", example=1.24) density: Optional[float] = Field(gt=0, description="The density of this filament in g/cm3.", example=1.24)

View File

@@ -82,8 +82,8 @@ class Filament(BaseModel):
) )
color_hex: Optional[str] = Field( color_hex: Optional[str] = Field(
min_length=6, min_length=6,
max_length=6, max_length=8,
description="Hexadecimal color code of the filament, e.g. FF0000 for red. (no leading #)", description="Hexadecimal color code of the filament, e.g. FF0000 for red. Supports alpha channel at the end.",
example="FF0000", example="FF0000",
) )

View File

@@ -41,7 +41,7 @@ class Filament(Base):
comment: Mapped[Optional[str]] = mapped_column(String(1024)) comment: Mapped[Optional[str]] = mapped_column(String(1024))
settings_extruder_temp: Mapped[Optional[int]] = mapped_column(comment="Overridden extruder temperature.") settings_extruder_temp: Mapped[Optional[int]] = mapped_column(comment="Overridden extruder temperature.")
settings_bed_temp: Mapped[Optional[int]] = mapped_column(comment="Overridden bed temperature.") settings_bed_temp: Mapped[Optional[int]] = mapped_column(comment="Overridden bed temperature.")
color_hex: Mapped[Optional[str]] = mapped_column(String(6)) color_hex: Mapped[Optional[str]] = mapped_column(String(8))
class Spool(Base): class Spool(Base):

View File

@@ -438,3 +438,23 @@ def test_update_filament_not_found():
assert "filament" in message assert "filament" in message
assert "id" in message assert "id" in message
assert "123456789" in message assert "123456789" in message
def test_add_filament_color_hex_alpha():
"""Test adding a filament with an alpha channel in the color hex."""
color_hex = "FF000088"
# Execute
result = httpx.post(
f"{URL}/api/v1/filament",
json={
"density": 1.25,
"diameter": 1.75,
"color_hex": color_hex,
},
)
result.raise_for_status()
# Verify
filament = result.json()
assert filament["color_hex"] == color_hex