fix: commit template upload atomically
This commit is contained in:
@@ -34,8 +34,9 @@ def upload_template(
|
||||
try:
|
||||
stored_path, content = store_template_file(file)
|
||||
blocks = parse_document(content)
|
||||
template = create_template_record(db, name=name, file_path=stored_path, type=type)
|
||||
save_template_blocks(db, template.id, blocks)
|
||||
template = create_template_record(db, name=name, file_path=stored_path, type=type, commit=False)
|
||||
save_template_blocks(db, template.id, blocks, commit=False)
|
||||
db.commit()
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
|
||||
@@ -46,16 +46,30 @@ def store_template_file(file: UploadFile) -> tuple[str, bytes]:
|
||||
return stored_path, content
|
||||
|
||||
|
||||
def create_template_record(db: Session, name: str, file_path: str, type: str = "report") -> Template:
|
||||
def create_template_record(
|
||||
db: Session,
|
||||
name: str,
|
||||
file_path: str,
|
||||
type: str = "report",
|
||||
commit: bool = True,
|
||||
) -> Template:
|
||||
"""创建模板记录"""
|
||||
tmpl = Template(name=name, type=type, original_file_path=file_path)
|
||||
db.add(tmpl)
|
||||
db.commit()
|
||||
if commit:
|
||||
db.commit()
|
||||
else:
|
||||
db.flush()
|
||||
db.refresh(tmpl)
|
||||
return tmpl
|
||||
|
||||
|
||||
def save_template_blocks(db: Session, template_id: int, blocks: list[dict]) -> list[TemplateBlock]:
|
||||
def save_template_blocks(
|
||||
db: Session,
|
||||
template_id: int,
|
||||
blocks: list[dict],
|
||||
commit: bool = True,
|
||||
) -> list[TemplateBlock]:
|
||||
"""批量保存解析出的模板区域。"""
|
||||
records = [
|
||||
TemplateBlock(
|
||||
@@ -74,5 +88,8 @@ def save_template_blocks(db: Session, template_id: int, blocks: list[dict]) -> l
|
||||
]
|
||||
|
||||
db.add_all(records)
|
||||
db.commit()
|
||||
if commit:
|
||||
db.commit()
|
||||
else:
|
||||
db.flush()
|
||||
return records
|
||||
|
||||
Reference in New Issue
Block a user