From 2d336cd1dad2123df6720d2f79e18cb3d5341fee Mon Sep 17 00:00:00 2001 From: Francisco Penedo Date: Wed, 24 Apr 2024 21:45:59 +0200 Subject: [PATCH] Fix book import failing due to strict validation --- src/hxbooks/book.py | 6 ++++- src/hxbooks/gbooks.py | 51 +++++++++++++++++++++++++++---------------- 2 files changed, 37 insertions(+), 20 deletions(-) diff --git a/src/hxbooks/book.py b/src/hxbooks/book.py index c5d11cb..0e7aa0b 100644 --- a/src/hxbooks/book.py +++ b/src/hxbooks/book.py @@ -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) diff --git a/src/hxbooks/gbooks.py b/src/hxbooks/gbooks.py index 370fb37..ad5985e 100644 --- a/src/hxbooks/gbooks.py +++ b/src/hxbooks/gbooks.py @@ -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: