Przeglądaj źródła

数据库路径修改为相对路径

AnlaAnla 1 miesiąc temu
rodzic
commit
3c38df955b
4 zmienionych plików z 18 dodań i 22 usunięć
  1. 4 2
      Test/test01.py
  2. 7 5
      app/api/cards.py
  3. 7 4
      app/api/images.py
  4. 0 11
      app/utils/scheme.py

+ 4 - 2
Test/test01.py

@@ -1,7 +1,8 @@
 import requests
 
+# base_url = 'http://127.0.0.1:7745/api/cards/query/1'
+base_url = 'http://192.168.31.243:7745/api/cards/query/4'
 
-base_url = 'http://192.168.31.243:7745/api/cards/query/3'
 
 def send(url):
     # 请求头 (headers)
@@ -33,5 +34,6 @@ def send(url):
     except requests.exceptions.RequestException as err:
         print(f"An Error Occurred: {err}")
 
+
 if __name__ == '__main__':
-    send(base_url)
+    send(base_url)

+ 7 - 5
app/api/cards.py

@@ -149,12 +149,14 @@ def delete_card(id: int, db_conn: PooledMySQLConnection = db_dependency):
 
         # 3. 删除物理文件
         for path in image_paths_to_delete:
-            if os.path.exists(path):
+            absolute_path = settings.BASE_PATH / path.lstrip('/\\')
+
+            if os.path.exists(absolute_path):
                 try:
-                    os.remove(path)
-                    logger.info(f"图片文件已删除: {path}")
+                    os.remove(absolute_path)
+                    logger.info(f"图片文件已删除: {absolute_path}")
                 except OSError as e:
-                    logger.error(f"删除文件失败 {path}: {e}")
+                    logger.error(f"删除文件失败 {absolute_path}: {e}")
 
         db_conn.commit()
         logger.info(f"ID {id} 的卡牌和关联数据已成功删除。")
@@ -167,4 +169,4 @@ def delete_card(id: int, db_conn: PooledMySQLConnection = db_dependency):
         raise HTTPException(status_code=500, detail="删除卡牌失败。")
     finally:
         if cursor:
-            cursor.close()
+            cursor.close()

+ 7 - 4
app/api/images.py

@@ -47,6 +47,7 @@ async def upload_image_for_card(
     file_extension = os.path.splitext(image.filename)[1]
     unique_filename = f"{uuid.uuid4()}{file_extension}"
     image_path = settings.DATA_DIR / unique_filename
+    relative_path = f"/{image_path.parent.name}/{image_path.name}"
     try:
         with open(image_path, "wb") as buffer:
             buffer.write(await image.read())
@@ -69,7 +70,7 @@ async def upload_image_for_card(
             "VALUES (%s, %s, %s, %s, %s)"
         )
         params = (
-        card_id, image_type.value, image_name, str(image_path), json.dumps(detection_json, ensure_ascii=False))
+        card_id, image_type.value, image_name, relative_path, json.dumps(detection_json, ensure_ascii=False))
 
         cursor.execute(query_insert_image, params)
         new_id = cursor.lastrowid
@@ -171,11 +172,13 @@ def get_image_file(id: int, db_conn: PooledMySQLConnection = db_dependency):
             raise HTTPException(status_code=404, detail=f"ID为 {id} 的记录未找到。")
 
         image_path = result[0]
-        if not os.path.exists(image_path):
-            logger.error(f"文件在服务器上未找到: {image_path} (数据库ID: {id})")
+        absolute_path = settings.BASE_PATH / image_path.lstrip('/\\')
+
+        if not os.path.exists(absolute_path):
+            logger.error(f"文件在服务器上未找到: {absolute_path} (数据库ID: {id})")
             raise HTTPException(status_code=404, detail="图片文件在服务器上不存在。")
 
-        return FileResponse(image_path)
+        return FileResponse(absolute_path)
     except Exception as e:
         logger.error(f"获取图片失败 ({id}): {e}")
         if isinstance(e, HTTPException): raise e

+ 0 - 11
app/utils/scheme.py

@@ -22,17 +22,6 @@ class CardImageResponse(BaseModel):
     class Config:
         from_attributes = True
 
-    @field_validator('image_path', mode='before')
-    @classmethod
-    def format_image_path(cls, v:str):
-        """将绝对文件路径转换为 'Data/filename.jpg' 格式的相对URL路径"""
-        if not isinstance(v, str) or not v:
-            return v
-        p = Path(v)
-        relative_path = f"{p.parent.name}/{p.name}"
-
-        return relative_path
-
     @field_validator('detection_json', 'modified_json', mode='before')
     @classmethod
     def parse_json_string(cls, v):