cards.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. from datetime import datetime
  2. import os
  3. from typing import Optional, List
  4. from fastapi import APIRouter, Depends, HTTPException, Query
  5. from mysql.connector.pooling import PooledMySQLConnection
  6. from app.core.config import settings
  7. from app.core.logger import get_logger
  8. from app.core.database_loader import get_db_connection
  9. from app.utils.scheme import CardDetailResponse, CardImageResponse, CardListDetailResponse
  10. logger = get_logger(__name__)
  11. router = APIRouter()
  12. db_dependency = Depends(get_db_connection)
  13. @router.post("/created", response_model=CardDetailResponse, status_code=201, summary="创建一个新的卡牌记录")
  14. def create_card(
  15. card_name: Optional[str] = Query(None, summary="卡牌的名称"),
  16. db_conn: PooledMySQLConnection = db_dependency
  17. ):
  18. """创建一个新的卡牌实体,此时它不关联任何图片。"""
  19. cursor = None
  20. try:
  21. cursor = db_conn.cursor()
  22. query = f"INSERT INTO {settings.DB_CARD_TABLE_NAME} (card_name) VALUES (%s)"
  23. cursor.execute(query, (card_name,))
  24. db_conn.commit()
  25. new_id = cursor.lastrowid
  26. logger.info(f"新卡牌已创建, ID: {new_id}")
  27. # 返回刚创建的空卡牌信息
  28. return CardDetailResponse(
  29. id=new_id,
  30. card_name=card_name,
  31. created_at=datetime.now(),
  32. updated_at=datetime.now(),
  33. images=[]
  34. )
  35. except Exception as e:
  36. db_conn.rollback()
  37. logger.error(f"创建卡牌失败: {e}")
  38. raise HTTPException(status_code=500, detail="数据库插入失败。")
  39. finally:
  40. if cursor:
  41. cursor.close()
  42. @router.get("/query/{id}", response_model=CardDetailResponse, summary="获取指定卡牌的详细信息")
  43. def get_card_details(id: int, db_conn: PooledMySQLConnection = db_dependency):
  44. """获取卡牌元数据以及所有与之关联的图片信息。"""
  45. cursor = None
  46. try:
  47. cursor = db_conn.cursor(dictionary=True)
  48. # 1. 获取卡牌信息
  49. query_card = f"SELECT * FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s"
  50. cursor.execute(query_card, (id,))
  51. card_data = cursor.fetchone()
  52. if not card_data:
  53. raise HTTPException(status_code=404, detail=f"ID为 {id} 的卡牌未找到。")
  54. # 2. 获取所有关联的图片信息
  55. query_images = f"SELECT * FROM {settings.DB_IMAGE_TABLE_NAME} WHERE card_id = %s"
  56. cursor.execute(query_images, (id,))
  57. image_records = cursor.fetchall()
  58. images = [CardImageResponse.model_validate(row) for row in image_records]
  59. # 组合成最终响应
  60. card_response = CardDetailResponse.model_validate(card_data)
  61. card_response.images = images
  62. return card_response
  63. except Exception as e:
  64. logger.error(f"查询卡牌详情失败 ({id}): {e}")
  65. if isinstance(e, HTTPException): raise e
  66. raise HTTPException(status_code=500, detail="数据库查询失败。")
  67. finally:
  68. if cursor:
  69. cursor.close()
  70. @router.get("/card_list", response_model=List[CardListDetailResponse], summary="获取卡牌列表")
  71. def list_cards_detailed(
  72. start_id: Optional[int] = Query(None, description="筛选条件:起始 card_id"),
  73. end_id: Optional[int] = Query(None, description="筛选条件:结束 card_id"),
  74. skip: int = Query(0, ge=0, description="分页:跳过的记录数"),
  75. limit: int = Query(100, ge=1, le=1000, description="分页:每页的记录数"),
  76. db_conn: PooledMySQLConnection = db_dependency
  77. ):
  78. """
  79. 获取卡牌的基础信息列表,支持按 id 范围筛选和分页。
  80. """
  81. cursor = None
  82. try:
  83. cursor = db_conn.cursor(dictionary=True)
  84. base_query = f"SELECT id, card_name, created_at, updated_at FROM {settings.DB_CARD_TABLE_NAME}"
  85. conditions = []
  86. params = []
  87. if start_id is not None:
  88. conditions.append("id >= %s")
  89. params.append(start_id)
  90. if end_id is not None:
  91. conditions.append("id <= %s")
  92. params.append(end_id)
  93. if conditions:
  94. base_query += " WHERE " + " AND ".join(conditions)
  95. base_query += " ORDER BY id DESC LIMIT %s OFFSET %s"
  96. params.extend([limit, skip])
  97. cursor.execute(base_query, tuple(params))
  98. results = cursor.fetchall()
  99. return [CardListDetailResponse.model_validate(row) for row in results]
  100. except Exception as e:
  101. logger.error(f"查询卡牌列表失败: {e}")
  102. raise HTTPException(status_code=500, detail="获取数据列表失败。")
  103. finally:
  104. if cursor:
  105. cursor.close()
  106. @router.delete("/delete/{id}", status_code=200, summary="删除卡牌及其所有关联图片")
  107. def delete_card(id: int, db_conn: PooledMySQLConnection = db_dependency):
  108. """
  109. 删除一张卡牌及其所有关联的图片记录和物理文件。
  110. 利用了数据库的 ON DELETE CASCADE 特性。
  111. """
  112. cursor = None
  113. try:
  114. cursor = db_conn.cursor()
  115. # 1. 查询所有关联图片的物理文件路径,以便稍后删除
  116. query_paths = f"SELECT image_path FROM {settings.DB_IMAGE_TABLE_NAME} WHERE card_id = %s"
  117. cursor.execute(query_paths, (id,))
  118. image_paths_to_delete = [row[0] for row in cursor.fetchall()]
  119. # 2. 删除卡牌记录。数据库会自动级联删除 card_images 表中的相关记录
  120. query_delete_card = f"DELETE FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s"
  121. cursor.execute(query_delete_card, (id,))
  122. if cursor.rowcount == 0:
  123. raise HTTPException(status_code=404, detail=f"ID为 {id} 的卡牌未找到。")
  124. # 3. 删除物理文件
  125. for path in image_paths_to_delete:
  126. if os.path.exists(path):
  127. try:
  128. os.remove(path)
  129. logger.info(f"图片文件已删除: {path}")
  130. except OSError as e:
  131. logger.error(f"删除文件失败 {path}: {e}")
  132. db_conn.commit()
  133. logger.info(f"ID {id} 的卡牌和关联数据已成功删除。")
  134. return {"message": f"成功删除卡牌 ID {id} 及其所有关联数据"}
  135. except Exception as e:
  136. db_conn.rollback()
  137. logger.error(f"删除卡牌失败 ({id}): {e}")
  138. if isinstance(e, HTTPException): raise e
  139. raise HTTPException(status_code=500, detail="删除卡牌失败。")
  140. finally:
  141. if cursor:
  142. cursor.close()