Fix book import failing due to strict validation

This commit is contained in:
2024-04-24 21:45:59 +02:00
parent 18d320422a
commit 2d336cd1da
2 changed files with 37 additions and 20 deletions

View File

@@ -182,7 +182,11 @@ def books_import() -> Response:
isbn=isbn,
authors=book_data.authors,
publisher=book_data.publisher,
first_published=book_data.publishedDate.year,
first_published=(
book_data.publishedDate.year
if isinstance(book_data.publishedDate, date)
else book_data.publishedDate
),
genres=book_data.categories,
)
db.session.add(book)

View File

@@ -1,7 +1,8 @@
from datetime import date
from datetime import date, datetime
from typing import Any, Optional
import requests
from pydantic import BaseModel
from pydantic import BaseModel, field_validator
# {
# "title": "Concilio de Sombras (Sombras de Magia 2)",
@@ -50,23 +51,35 @@ from pydantic import BaseModel
class GoogleBook(BaseModel):
title: str
authors: list[str]
publisher: str
publishedDate: date
description: str
industryIdentifiers: list[dict[str, str]]
pageCount: int
printType: str
categories: list[str]
maturityRating: str
allowAnonLogging: bool
contentVersion: str
panelizationSummary: dict[str, bool]
imageLinks: dict[str, str]
language: str
previewLink: str
infoLink: str
canonicalVolumeLink: str
authors: list[str] = []
publisher: str = ""
publishedDate: Optional[date | int] = None
description: str = ""
industryIdentifiers: list[dict[str, str]] = []
pageCount: int = 0
printType: str = ""
categories: list[str] = []
maturityRating: str = ""
allowAnonLogging: bool = False
contentVersion: str = ""
panelizationSummary: dict[str, bool] = {}
imageLinks: dict[str, str] = {}
language: str = ""
previewLink: str = ""
infoLink: str = ""
canonicalVolumeLink: str = ""
# Validate publishedDate when given in YYYY-MM format and convert to date
@field_validator("publishedDate", mode="before")
@classmethod
def validate_published_date(cls, v: Any) -> Any:
if isinstance(v, str):
try:
return datetime.strptime(v, "%Y-%m").date()
except ValueError:
pass
return v
def fetch_google_book_data(isbn: str) -> GoogleBook: