1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import os
- from typing import Union
- from fastapi import APIRouter, UploadFile, File, Depends
- from sqlalchemy.ext.asyncio import AsyncSession
- from common.common import upload_oss_file, delete_oss_file
- from core.config import settings
- from crud.marktask import crud_task
- from crud.paper import crud_paper
- from models.user import Student, Teacher, Admin
- from schemas.base import DetailMixin
- from schemas.common import DeleteFile, UploadBase64File
- from utils.depends import get_current_user, get_async_db
- router = APIRouter()
- @router.post("/upfile",
- response_model=DetailMixin,
- response_model_exclude_none=True,
- summary="通用文件上传")
- async def upload_file(datafile: UploadFile = File(..., description="文件"),
- current_user: Union[Admin, Teacher, Student] = Depends(get_current_user)):
- ok, url = await upload_oss_file(datafile, content_type={"Content-Type": datafile.content_type})
- if ok:
- return {"data": url}
- else:
- return {"errcode": 400, "mess": url}
- @router.post("/upfile/base64",
- response_model=DetailMixin,
- response_model_exclude_none=True,
- summary="通用文件上传(base64)")
- async def upload_base64_file(datafile: UploadBase64File,
- current_user: Union[Admin, Teacher,
- Student] = Depends(get_current_user)):
- content_type = datafile.content[:22].split(";")[0].split(":")[-1]
- ok, url = await upload_oss_file(datafile, content_type={"Content-Type": content_type})
- if ok:
- return {"data": url}
- else:
- return {"errcode": 400, "mess": url}
- @router.post("/delfile",
- response_model=DetailMixin,
- response_model_exclude_none=True,
- tags=["通用接口"],
- summary="通用文件删除")
- async def delete_file(info: DeleteFile,
- current_user: Union[Admin, Teacher, Student] = Depends(get_current_user)):
- ok, url = await delete_oss_file(info.path)
- if ok:
- return {"data": None}
- else:
- return {"errcode": 400, "mess": url}
- @router.post("/uppapers", summary="试卷上传")
- async def upload_file(datafile: UploadFile = File(..., description="文件"),
- db: AsyncSession = Depends(get_async_db)):
- content = await datafile.read()
- filename = datafile.filename
- tid = filename.split("_")[0]
- task = await crud_task.find_one(db, filters={"id": tid})
- if task:
- pid = task.pid
- paper = await crud_paper.find_one(db, filters={"id": pid})
- if paper:
- pno = paper.pno
- root = os.path.join(settings.PAPERS_PATH, f"T{tid}-{pno}")
- if not os.path.exists(root):
- os.makedirs(root)
- filepath = os.path.join(root, filename)
- with open(filepath, "wb") as f:
- f.write(content)
- return {"data": filepath}
- return {"errcode": 400, "mess": "上传失败!"}
|