添加API路由模块
This commit is contained in:
61
api/routers/books.py
Normal file
61
api/routers/books.py
Normal file
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
回忆录相关 API 路由
|
||||
"""
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from database import get_async_db
|
||||
from database.models import Book as BookModel
|
||||
from services.pdf_service import pdf_service
|
||||
|
||||
router = APIRouter(prefix="/api/books", tags=["books"])
|
||||
|
||||
|
||||
@router.get("/current")
|
||||
async def get_current_book(
|
||||
user_id: str,
|
||||
db: AsyncSession = Depends(get_async_db)
|
||||
):
|
||||
"""获取当前回忆录"""
|
||||
stmt = select(BookModel).where(BookModel.user_id == user_id).order_by(BookModel.updated_at.desc())
|
||||
result = await db.execute(stmt)
|
||||
book = result.scalar_one_or_none()
|
||||
|
||||
if not book:
|
||||
return {"message": "No book found"}
|
||||
|
||||
return {
|
||||
"id": book.id,
|
||||
"title": book.title,
|
||||
"total_pages": book.total_pages,
|
||||
"total_words": book.total_words,
|
||||
"cover_image_url": book.cover_image_url
|
||||
}
|
||||
|
||||
|
||||
@router.post("/export-pdf")
|
||||
async def export_pdf(
|
||||
book_id: str,
|
||||
user_id: str,
|
||||
db: AsyncSession = Depends(get_async_db)
|
||||
):
|
||||
"""导出 PDF"""
|
||||
book = await db.get(BookModel, book_id)
|
||||
if not book or book.user_id != user_id:
|
||||
raise HTTPException(status_code=404, detail="Book not found")
|
||||
|
||||
# 获取所有章节
|
||||
from ..database.models import Chapter
|
||||
stmt = select(Chapter).where(Chapter.user_id == user_id).order_by(Chapter.order_index)
|
||||
result = await db.execute(stmt)
|
||||
chapters = result.scalars().all()
|
||||
|
||||
# 生成 PDF
|
||||
pdf_bytes = await pdf_service.generate_pdf(book, chapters)
|
||||
|
||||
return {
|
||||
"pdf_base64": pdf_bytes.decode('latin1'), # 简化处理,实际应该用 base64
|
||||
"filename": f"{book.title}.pdf"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user