Google Books API 允许开发者通过编程方式访问 Google 图书的相关信息。以下是一个简化的模型类示例,用于表示从 Google Books API 返回的数据。请注意,实际的 API 可能返回更多的字段,这里仅展示了部分常用字段。
import json
class GoogleBook:
def __init__(self, json_data):
self.id = json_data.get('id', '')
self.title = json_data.get('title', '')
self.authors = json_data.get('authors', [])
self.published_date = json_data.get('publishedDate', '')
self.publisher = json_data.get('publisher', '')
self.description = json_data.get('description', '')
self.page_count = json_data.get('pageCount', 0)
self.image_links = json_data.get('imageLinks', {})
self.language = json_data.get('language', '')
def get_image_url(self, size='thumbnail'):
if 'imageLinks' in self.image_links and size in self.image_links:
return self.image_links[size]
return None
def to_dict(self):
return {
'id': self.id,
'title': self.title,
'authors': self.authors,
'published_date': self.published_date,
'publisher': self.publisher,
'description': self.description,
'page_count': self.page_count,
'image_url': self.get_image_url(),
'language': self.language
}
@classmethod
def from_json(cls, json_string):
json_data = json.loads(json_string)
return cls(json_data)
def __str__(self):
return f"{self.title} by {', '.join(self.authors)} ({self.published_date})"
import requests
def fetch_book_info(isbn):
url = f"https://www.googleapis.com/books/v1/volumes?q=isbn:{isbn}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if 'items' in data and len(data['items']) > 0:
book_data = data['items'][0]['volumeInfo']
book = GoogleBook(book_data)
print(book)
return book
else:
print("No books found.")
else:
print("Failed to fetch book info.")
# 示例:通过 ISBN 获取书籍信息
fetch_book_info('9780132350884')
__init__
: 初始化方法,从 JSON 数据中提取常用字段。get_image_url
: 获取书籍封面的 URL,默认返回缩略图。to_dict
: 将书籍信息转换为字典格式,便于序列化。from_json
: 类方法,从 JSON 字符串创建 GoogleBook
实例。__str__
: 返回书籍的基本信息字符串。GoogleBook
实例。这个模型类可以根据实际需求进行扩展,以支持更多的字段和功能。