添加主题列表增删改查,主题文件模板增删改查,主题文件上传修改接口

This commit is contained in:
wcq 2023-12-07 14:48:06 +08:00
parent b1fa11fc9f
commit 65e1d6c84e
9 changed files with 459 additions and 35 deletions

View File

@ -102,3 +102,5 @@ email_tool = EmailTool(**dict(conf['email_tool']))
# 邮箱验证码工具类 # 邮箱验证码工具类
email_verify_code = EmailVerifyCode(redis_pool, email_tool) email_verify_code = EmailVerifyCode(redis_pool, email_tool)
static_path = Path('static')

View File

@ -5,7 +5,7 @@ from random import random
from typing import Set from typing import Set
from sqlalchemy import String, DateTime, func, Boolean, JSON, ForeignKey, Enum, TEXT, Double, Integer, create_engine from sqlalchemy import String, DateTime, func, Boolean, JSON, ForeignKey, Enum, TEXT, Double, Integer, create_engine
from sqlalchemy.orm import mapped_column, Mapped, declarative_base, relationship from sqlalchemy.orm import mapped_column, Mapped, declarative_base, relationship
from mods.rate.schemas import ReceiveSubjectState, ReceiveOrderState, NoticeType from .schemas import ReceiveSubjectState, ReceiveOrderState, NoticeType
from utils.random_utils import get_random_letter_and_num_code, get_random_num_code, time_now_to_code from utils.random_utils import get_random_letter_and_num_code, get_random_num_code, time_now_to_code
from utils.sqlalchemy_common_utils import SalBase from utils.sqlalchemy_common_utils import SalBase
from .common import Base from .common import Base
@ -23,8 +23,7 @@ class ReceiveSubjectFile(Base, SalBase):
""" """
__tablename__ = "receive_subject_file" __tablename__ = "receive_subject_file"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment='id') id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment='id')
subject_id: Mapped[int] = mapped_column(ForeignKey("receive_subject.id", ondelete="CASCADE", onupdate="CASCADE"), subject_id: Mapped[int] = mapped_column(ForeignKey("receive_subject.id", ondelete="CASCADE", onupdate="CASCADE"),comment="主题ID", nullable=False)
comment="主题ID", nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False, comment='名称') name: Mapped[str] = mapped_column(String(255), nullable=False, comment='名称')
type: Mapped[str] = mapped_column(String(255), nullable=False, comment='类型') type: Mapped[str] = mapped_column(String(255), nullable=False, comment='类型')
des: Mapped[str] = mapped_column(TEXT, nullable=True, comment='说明') des: Mapped[str] = mapped_column(TEXT, nullable=True, comment='说明')
@ -39,6 +38,7 @@ class ReceiveSubject(Base, SalBase):
__tablename__ = "receive_subject" __tablename__ = "receive_subject"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment='主题ID') id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment='主题ID')
name: Mapped[str] = mapped_column(String(255), nullable=False, unique=True, comment='主题名称') name: Mapped[str] = mapped_column(String(255), nullable=False, unique=True, comment='主题名称')
receiver: Mapped[str] = mapped_column(String(255), nullable=False, comment='接收人')
start_time: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=True, start_time: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=True,
comment='开始时间') comment='开始时间')
finish_time: Mapped[datetime] = mapped_column(DateTime, nullable=True, finish_time: Mapped[datetime] = mapped_column(DateTime, nullable=True,

View File

@ -10,14 +10,15 @@ class ReceiveSubjectId(BaseModel):
class ReceiveSubjectAdd(BaseModel): class ReceiveSubjectAdd(BaseModel):
name: str name: str
start_time: Optional[datetime]= None start_time: Optional[datetime] = None
finish_time: Optional[datetime]= None finish_time: Optional[datetime] = None
state: Any receiver: str
folder_name: Optional[str]= None state: Any
create_time: Optional[datetime]= None folder_name: Optional[str] = None
des: Any create_time: Optional[datetime] = None
files: Optional[List[Any]]= None des: Any
files: Optional[List[Any]] = None
class ReceiveSubjectAddOptional(ReceiveSubjectAdd, metaclass=AllOptional): class ReceiveSubjectAddOptional(ReceiveSubjectAdd, metaclass=AllOptional):

View File

@ -34,3 +34,4 @@ def receive_subject_file_get(db: Session, data: schemas.ReceiveSubjectFileId) ->
def receive_subject_file_all(db: Session): def receive_subject_file_all(db: Session):
return db.query(ReceiveSubjectFile).all() return db.query(ReceiveSubjectFile).all()

View File

@ -1,9 +1,14 @@
from fastapi import APIRouter, Depends, HTTPException import json
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from context.common import static_path
from ...common import get_db from ...common import get_db
from . import crud from . import crud
from . import schemas from . import schemas
from ...models import ReceiveSubject
from ...utils import get_upload_file_type, file_upload
router = APIRouter(tags=["主题文件模板"], prefix='/receive_subject_file') router = APIRouter(tags=["主题文件模板"], prefix='/receive_subject_file')
@ -43,11 +48,34 @@ def receive_subject_file_query(req: schemas.ReceiveSubjectFileQueryReq, db: Sess
return schemas.ReceiveSubjectFileQueryRes(count=count, items=items) return schemas.ReceiveSubjectFileQueryRes(count=count, items=items)
@router.post("/all", summary="获取所有主题文件模板", response_model=schemas.ReceiveSubjectFileAllRes) @router.post("/add_with_file", summary="添加主题文件模板附带文件")
def receive_subject_file_all(req: schemas.ReceiveSubjectFileAllReq, db: Session = Depends(get_db)): def receive_subject_file_add_with_file(file: UploadFile = File(...), data: str = Form(...),
query = crud.receive_subject_file_all(db) db: Session = Depends(get_db)):
items = [schemas.ReceiveSubjectFileInfo(**item.to_full_dict(include=req.include, file_type = get_upload_file_type(file)
ex_include=req.ex_include, data = json.loads(data)
relation_use_id=req.relation_use_id)) for item in query] data['template_path'] = ''
return schemas.ReceiveSubjectFileAllRes(items=items) data['type'] = file_type
req = schemas.ReceiveSubjectFileAddReq(**data)
subject: ReceiveSubject = db.query(ReceiveSubject).filter(ReceiveSubject.id == req.D).first()
folder_name = subject.folder_name
file_path = file_upload(file, static_path / folder_name, db)
req.template_path = file_path
item = crud.receive_subject_file_add(db, req)
return schemas.ReceiveSubjectFileAddRes(**item.to_dict())
@router.post("/update_file", summary="修改主题文件模板附带文件")
def receive_subject_file_update_file(file: UploadFile = File(...), data: str = Form(...),
db: Session = Depends(get_db)):
data = json.loads(data)
file_type = get_upload_file_type(file)
req = schemas.ReceiveSubjectFileUpdate(
**{'id': data['id'], 'template_path': '', 'type': file_type, 'subject_id': data['subject_id']})
subject: ReceiveSubject = db.query(ReceiveSubject).filter(ReceiveSubject.id == req.subject_id).first()
folder_name = subject.folder_name
file_path = file_upload(file, static_path / folder_name, db)
req.template_path = file_path
item = crud.receive_subject_file_update(db, req)
return schemas.ReceiveSubjectFileUpdateRes(**item.to_dict())
######### #########

View File

@ -12,7 +12,7 @@ class ReceiveSubjectFileId(BaseModel):
class ReceiveSubjectFileAdd(BaseModel): class ReceiveSubjectFileAdd(BaseModel):
name: str name: str
subject_id: int subject_id: int
type: str type: Optional[str] = None
des: Any des: Any
template_path: Optional[str] = None template_path: Optional[str] = None
file_size_limit: Optional[float] = None file_size_limit: Optional[float] = None

File diff suppressed because one or more lines are too long

View File

@ -1,28 +1,28 @@
from enum import Enum from enum import Enum
class RateServeState(Enum): class ReceiveSubjectState(Enum):
""" """
评级服务状态类型 接收主题状态
""" """
examining = 'examining' # 审核中 receiving = 'receiving' # 接收种
rating = 'rating' # 评级中 examining = 'examining' # 处理种
cancel = 'cancel' # 取消
finish = 'finish' # 完成 finish = 'finish' # 完成
class NodeState(Enum): class ReceiveOrderState(Enum):
""" """
节点状态 接收主题状态
""" """
incomplete = "incomplete" # 未完成 receiving = 'receiving' # 接收种
finish = "finish" # 完成 examining = 'examining' # 处理种
finish = 'finish' # 完成
class FileSubType: class NoticeType(Enum):
""" """
文件分类,不使用Enum,因为类型不限制 通知类型
""" """
report = 'report' # 报告 phone = 'phone'
cert = 'cert' # 证书 email = 'email'
fill_sheet = 'fill_sheet' # 企业填报文件

43
mods/receive/utils.py Normal file
View File

@ -0,0 +1,43 @@
import os
from pathlib import Path
from fastapi import UploadFile
from sqlalchemy.orm import Session
from mimetypes import types_map
from utils.common_utils import file_md5
types_map['.xlsx'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
types_map['.docx'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
types_dic = {key[1:]: item for key, item in types_map.items()}
types_dic_rev = {item: key[1:] for key, item in types_map.items()}
def get_upload_file_type(file: UploadFile, ):
file_type = types_dic_rev.get(file.content_type)
return file_type
def file_upload(file: UploadFile, save_path: str, db: Session, user_id=None, sub_type=''):
content = b""
while True:
byte = file.file.read(10240)
if byte:
content += byte
else:
break
content_type = file.content_type
file_type = get_upload_file_type(file)
common_type, _ = content_type.split('/')
content_start = content[0:10240]
file_md = file_md5(content_start)
file_save_name = file_md + f".{file_type}"
save_path = Path(save_path)
file_save_path = save_path / file_save_name
file_url = file_save_path.__str__()
if not os.path.exists(save_path):
os.makedirs(save_path)
if not os.path.exists(file_save_path):
with open(file_save_path, 'wb') as f:
f.write(content)
return file_url