fix: validate import identities and selected materials consistently
This commit is contained in:
@@ -3,7 +3,7 @@ from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -67,16 +67,33 @@ class FileConfirm(BaseModel):
|
||||
|
||||
class ProjectConfirm(BaseModel):
|
||||
relative_dir: str
|
||||
student_no: str = Field(pattern=r"^\d{5,20}$")
|
||||
student_no: str = Field(pattern=r"^[0-9]{5,20}$")
|
||||
name: str = Field(min_length=1)
|
||||
topic: str = Field(min_length=1)
|
||||
direction: str = ""
|
||||
files: list[FileConfirm]
|
||||
files: list[FileConfirm] = Field(min_length=1)
|
||||
|
||||
@field_validator("student_no", "name", "topic", "direction", mode="before")
|
||||
@classmethod
|
||||
def trim_identity(cls, value):
|
||||
return value.strip() if isinstance(value, str) else value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_selection(self):
|
||||
selected = [file for file in self.files if file.status != "ignored"]
|
||||
if not selected:
|
||||
raise ValueError("至少选择1份资料")
|
||||
categories = [file.category for file in selected]
|
||||
if any(category not in CATEGORIES for category in categories):
|
||||
raise ValueError("请选择有效材料类型")
|
||||
if len(set(categories)) != len(categories):
|
||||
raise ValueError("每类材料只允许选择1份,其余请设为忽略")
|
||||
return self
|
||||
|
||||
|
||||
class ImportConfirm(BaseModel):
|
||||
course_version_id: int
|
||||
projects: list[ProjectConfirm]
|
||||
projects: list[ProjectConfirm] = Field(min_length=1)
|
||||
|
||||
|
||||
class BatchInput(BaseModel):
|
||||
|
||||
Reference in New Issue
Block a user