添加行业分类信息相关接口

This commit is contained in:
wcq 2023-03-23 16:08:39 +08:00
parent ccc0b38338
commit 646810ee60
14 changed files with 443 additions and 0 deletions

View File

@ -0,0 +1,57 @@
from sqlalchemy.orm import Session
from . import Schemas
from .Models import IndustryMain
def industry_main_add(db: Session, data: Schemas.IndustryMainAddInfo):
item = IndustryMain(**data.dict())
db.add(item)
db.commit()
db.refresh(item)
return item
def industry_main_delete(db: Session, item_id: int):
db.query(IndustryMain).filter_by(code=item_id).delete()
db.commit()
def industry_main_update(db: Session, data: Schemas.IndustryMainUpdateInfo):
db.query(IndustryMain).filter_by(code=data.code).update({key: v for key, v in data.dict().items() if v is not None})
db.commit()
item = db.query(IndustryMain).filter_by(code=data.code).first()
return item
def industry_main_get(db: Session, item_id: int):
item = db.query(IndustryMain).filter_by(code=item_id).first()
return item
def industry_main_query(db: Session, params: Schemas.IndustryMainQuery):
params_dict = params.dict()
query = db.query(IndustryMain)
db_model = IndustryMain
for key, value in params_dict.items():
if key not in ['page', 'page_size'] and value is not None:
if type(value) == str:
query = query.filter(getattr(db_model, key).like(f'%{value}%'))
elif type(value) in [int, float, bool]:
query = query.filter_by(**{key: value})
else:
query = query.filter(getattr(db_model, key) == value)
count = query.count()
page = None
page_size = None
if 'page' in params_dict:
page = params_dict['page']
if 'page_size' in params_dict:
page_size = params_dict['page_size']
# 页数不超过100
page_size = min(page_size, 100)
if page is not None and page_size is not None:
query = query.offset((page - 1) * page_size).limit(page_size).all()
return count, query
################

View File

@ -0,0 +1,18 @@
from sqlalchemy.orm import relationship
from Context.common import common_db
from sqlalchemy import Column, Integer, String, ForeignKey, Text, DateTime, func
class IndustryMain(common_db.Base):
"""
行业分类表
"""
__tablename__ = "industry_main"
code = Column(Integer, primary_key=True)
type = Column(String(255), comment="类型")
name = Column(String(255), comment="名称")
belong = Column(Integer, comment="上级")
def to_dict(self):
data = {c.name: getattr(self, c.name) for c in self.__table__.columns}
return data

View File

@ -0,0 +1,43 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from Context.common import common_db
from . import Schemas
from . import Crud
router = APIRouter(tags=["行业分类"])
@router.post("/industry_main/add", summary="添加行业分类", response_model=Schemas.IndustryMainAddRes)
def industry_main_add(req: Schemas.IndustryMainAddReq, db: Session = Depends(common_db.get_db)):
item = Crud.industry_main_add(db, req)
return Schemas.IndustryMainAddRes(**item.to_dict())
@router.post("/industry_main/delete", summary="删除行业分类")
def industry_main_delete(req: Schemas.IndustryMainDeleteReq, db: Session = Depends(common_db.get_db)):
Crud.industry_main_delete(db, req.code)
return "删除成功"
@router.post("/industry_main/update", summary="更新行业分类", response_model=Schemas.IndustryMainUpdateRes)
def industry_main_update(req: Schemas.IndustryMainUpdateReq, db: Session = Depends(common_db.get_db)):
item = Crud.industry_main_update(db, req)
return Schemas.IndustryMainUpdateRes(**item.to_dict())
@router.post("/industry_main/get", summary="获取行业分类", response_model=Schemas.IndustryMainGetRes)
def industry_main_get(req: Schemas.IndustryMainGetReq, db: Session = Depends(common_db.get_db)):
item = Crud.industry_main_get(db, req.code)
if not item:
raise HTTPException(detail="未查询到信息", status_code=404)
return Schemas.IndustryMainGetRes(**item.to_dict())
@router.post("/industry_main/query", summary="查询行业分类", response_model=Schemas.IndustryMainQueryRes)
def industry_main_query(req: Schemas.IndustryMainQueryReq, db: Session = Depends(common_db.get_db)):
count, query = Crud.industry_main_query(db, req)
items = [Schemas.IndustryMainInfo(**item.to_dict()) for item in query]
return Schemas.IndustryMainQueryRes(count=count, items=items)
#########

View File

@ -0,0 +1,64 @@
from datetime import datetime
from pydantic import BaseModel
from typing import Optional, List
class IndustryMainInfo(BaseModel):
code: Optional[int]
belong: Optional[int]
name: Optional[str]
type: Optional[str]
class IndustryMainAddInfo(BaseModel):
code: Optional[int]
belong: Optional[int]
name: Optional[str]
type: Optional[str]
class IndustryMainAddReq(IndustryMainAddInfo):
pass
class IndustryMainAddRes(IndustryMainInfo):
pass
class IndustryMainUpdateInfo(IndustryMainInfo):
pass
class IndustryMainUpdateReq(IndustryMainUpdateInfo):
pass
class IndustryMainUpdateRes(IndustryMainInfo):
pass
class IndustryMainQuery(IndustryMainInfo):
pass
class IndustryMainQueryReq(IndustryMainQuery):
pass
class IndustryMainGetReq(BaseModel):
code: int
class IndustryMainGetRes(IndustryMainInfo):
pass
class IndustryMainQueryRes(BaseModel):
count: int
items: List[IndustryMainInfo]
class IndustryMainDeleteReq(BaseModel):
code: int
#######################

View File

@ -0,0 +1,57 @@
from sqlalchemy.orm import Session
from . import Schemas
from .Models import ProductMain
def product_main_add(db: Session, data: Schemas.ProductMainAddInfo):
item = ProductMain(**data.dict())
db.add(item)
db.commit()
db.refresh(item)
return item
def product_main_delete(db: Session, item_id: int):
db.query(ProductMain).filter_by(code=item_id).delete()
db.commit()
def product_main_update(db: Session, data: Schemas.ProductMainUpdateInfo):
db.query(ProductMain).filter_by(code=data.code).update({key: v for key, v in data.dict().items() if v is not None})
db.commit()
item = db.query(ProductMain).filter_by(code=data.code).first()
return item
def product_main_get(db: Session, item_id: int):
item = db.query(ProductMain).filter_by(code=item_id).first()
return item
def product_main_query(db: Session, params: Schemas.ProductMainQuery):
params_dict = params.dict()
query = db.query(ProductMain)
db_model = ProductMain
for key, value in params_dict.items():
if key not in ['page', 'page_size'] and value is not None:
if type(value) == str:
query = query.filter(getattr(db_model, key).like(f'%{value}%'))
elif type(value) in [int, float, bool]:
query = query.filter_by(**{key: value})
else:
query = query.filter(getattr(db_model, key) == value)
count = query.count()
page = None
page_size = None
if 'page' in params_dict:
page = params_dict['page']
if 'page_size' in params_dict:
page_size = params_dict['page_size']
# 页数不超过100
page_size = min(page_size, 100)
if page is not None and page_size is not None:
query = query.offset((page - 1) * page_size).limit(page_size).all()
return count, query
################

View File

@ -0,0 +1,18 @@
from sqlalchemy.orm import relationship
from Context.common import common_db
from sqlalchemy import Column, Integer, String, ForeignKey, Text, DateTime, func
class ProductMain(common_db.Base):
"""
产品分类表
"""
__tablename__ = "product_main"
code = Column(String(128), primary_key=True)
type = Column(String(128), comment="类型")
name = Column(String(128), comment="名称")
belong = Column(String(128), comment="上级")
def to_dict(self):
data = {c.name: getattr(self, c.name) for c in self.__table__.columns}
return data

View File

@ -0,0 +1,43 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from Context.common import common_db
from . import Schemas
from . import Crud
router = APIRouter(tags=["产品分类"])
@router.post("/product_main/add", summary="添加产品分类", response_model=Schemas.ProductMainAddRes)
def product_main_add(req: Schemas.ProductMainAddReq, db: Session = Depends(common_db.get_db)):
item = Crud.product_main_add(db, req)
return Schemas.ProductMainAddRes(**item.to_dict())
@router.post("/product_main/delete", summary="删除产品分类")
def product_main_delete(req: Schemas.ProductMainDeleteReq, db: Session = Depends(common_db.get_db)):
Crud.product_main_delete(db, req.code)
return "删除成功"
@router.post("/product_main/update", summary="更新产品分类", response_model=Schemas.ProductMainUpdateRes)
def product_main_update(req: Schemas.ProductMainUpdateReq, db: Session = Depends(common_db.get_db)):
item = Crud.product_main_update(db, req)
return Schemas.ProductMainUpdateRes(**item.to_dict())
@router.post("/product_main/get", summary="获取产品分类", response_model=Schemas.ProductMainGetRes)
def product_main_get(req: Schemas.ProductMainGetReq, db: Session = Depends(common_db.get_db)):
item = Crud.product_main_get(db, req.code)
if not item:
raise HTTPException(detail="未查询到信息", status_code=404)
return Schemas.ProductMainGetRes(**item.to_dict())
@router.post("/product_main/query", summary="查询产品分类", response_model=Schemas.ProductMainQueryRes)
def product_main_query(req: Schemas.ProductMainQueryReq, db: Session = Depends(common_db.get_db)):
count, query = Crud.product_main_query(db, req)
items = [Schemas.ProductMainInfo(**item.to_dict()) for item in query]
return Schemas.ProductMainQueryRes(count=count, items=items)
#########

View File

@ -0,0 +1,64 @@
from datetime import datetime
from pydantic import BaseModel
from typing import Optional, List
class ProductMainInfo(BaseModel):
code: Optional[int]
belong: Optional[int]
name: Optional[str]
type: Optional[str]
class ProductMainAddInfo(BaseModel):
code: Optional[int]
belong: Optional[int]
name: Optional[str]
type: Optional[str]
class ProductMainAddReq(ProductMainAddInfo):
pass
class ProductMainAddRes(ProductMainInfo):
pass
class ProductMainUpdateInfo(ProductMainInfo):
pass
class ProductMainUpdateReq(ProductMainUpdateInfo):
pass
class ProductMainUpdateRes(ProductMainInfo):
pass
class ProductMainQuery(ProductMainInfo):
pass
class ProductMainQueryReq(ProductMainQuery):
pass
class ProductMainGetReq(BaseModel):
code: int
class ProductMainGetRes(ProductMainInfo):
pass
class ProductMainQueryRes(BaseModel):
count: int
items: List[ProductMainInfo]
class ProductMainDeleteReq(BaseModel):
code: int
#######################

View File

@ -1,3 +1,5 @@
import json
from fastapi import APIRouter, Depends
from .Mods.OpinionInformation import Router as OpinionInformationRouter
from Context.common import auth_util
@ -7,3 +9,13 @@ router = APIRouter(
dependencies=[Depends(auth_util.token_data_depend)]
)
router.include_router(OpinionInformationRouter.router)
@router.get('/industry_main/all_json', tags=['分类信息'], summary="行业分类")
def industry_main_all_json():
return json.load(open('static/industry_main.json', 'r', encoding='utf-8'))
@router.get('/product_main/all_json', tags=['分类信息'], summary="产品分类")
def product_main_all_json():
return json.load(open('static/product_main.json', 'r', encoding='utf-8'))

View File

@ -98,3 +98,26 @@ def query_common_core(model, query, param_list: List[QueryParam]):
if query_type == "range":
query = query.filter(and_(column >= value[0], column <= value[1]))
return query
def tree_table_to_json(db: Session, model, belong_str='belong', key_str='id'):
"""
树结构数据库存储到json
"""
item_list = db.query(model).all()
node_list = []
for item in item_list:
item_dic = item.to_dict()
item_dic['children'] = []
node_list.append(item_dic)
nodes_dic = {node[key_str]: node for node in node_list}
tree = []
for node in node_list:
belong = node[belong_str]
if belong:
if belong in nodes_dic:
nodes_dic[belong]['children'].append(node)
else:
tree.append(node)
return tree

40
init.py Normal file
View File

@ -0,0 +1,40 @@
# 初始化数据创建、只需要调用一次的接口
import json
from Context.common import common_db
from Mods.CommonInformation.Mods.IndustryMain.Models import IndustryMain
from Mods.CommonInformation.Mods.ProductMain.Models import ProductMain
from Utils.PrintUtils import print_error
from Utils.SqlAlchemyUtils import tree_table_to_json
def save_industry_main_json():
"""
保存行业分类数据
"""
db = common_db.get_db_i()
try:
tree = tree_table_to_json(db, IndustryMain, key_str='code')
json.dump({'data': tree}, open('static/industry_main.json', 'w', encoding="utf-8"), ensure_ascii=False, )
except Exception as e:
print_error(e)
finally:
db.close()
def save_product_main_json():
"""
保存产品分类数据
"""
db = common_db.get_db_i()
try:
tree = tree_table_to_json(db, ProductMain, key_str='code')
json.dump({'data': tree}, open('static/product_main.json', 'w', encoding="utf-8"), ensure_ascii=False, )
except Exception as e:
print_error(e)
finally:
db.close()
save_industry_main_json()
save_product_main_json()

View File

@ -12,6 +12,8 @@ from Mods.OtherInformation import Router as OtherInformationRouter
from Mods.CommonInformation import Router as CommonInformationRouter
from Mods.RegionalEconomies import Router as RegionalEconomiesRouter
from Utils.RecordUtils import record_middleware
# 只需引用一次,后面将其注释
import init
common_db.init_database()
app = FastAPI(

File diff suppressed because one or more lines are too long

1
static/product_main.json Normal file
View File

@ -0,0 +1 @@
{"data": [{"code": "A", "type": "一级分类", "name": "货物", "belong": null, "children": [{"code": "A01000000", "type": "二级分类", "name": "房屋和构筑物", "belong": "A", "children": []}, {"code": "A02000000", "type": "二级分类", "name": "设备", "belong": "A", "children": []}, {"code": "A03000000", "type": "二级分类", "name": "文物和陈列品", "belong": "A", "children": []}, {"code": "A04000000", "type": "二级分类", "name": "图书和档案", "belong": "A", "children": []}, {"code": "A05000000", "type": "二级分类", "name": "家具和用具", "belong": "A", "children": []}, {"code": "A06000000", "type": "二级分类", "name": "特种动植物", "belong": "A", "children": []}, {"code": "A07000000", "type": "二级分类", "name": "物资", "belong": "A", "children": []}, {"code": "A08000000", "type": "二级分类", "name": "无形资产", "belong": "A", "children": []}]}, {"code": "B", "type": "一级分类", "name": "工程", "belong": null, "children": [{"code": "B01000000", "type": "二级分类", "name": "房屋施工", "belong": "B", "children": []}, {"code": "B02000000", "type": "二级分类", "name": "构筑物施工", "belong": "B", "children": []}, {"code": "B03000000", "type": "二级分类", "name": "施工工程准备", "belong": "B", "children": []}, {"code": "B04000000", "type": "二级分类", "name": "预制构件组装和装配", "belong": "B", "children": []}, {"code": "B05000000", "type": "二级分类", "name": "专业施工", "belong": "B", "children": []}, {"code": "B06000000", "type": "二级分类", "name": "安装工程", "belong": "B", "children": []}, {"code": "B07000000", "type": "二级分类", "name": "装修工程", "belong": "B", "children": []}, {"code": "B08000000", "type": "二级分类", "name": "修缮工程", "belong": "B", "children": []}, {"code": "B09000000", "type": "二级分类", "name": "工程设备租赁", "belong": "B", "children": []}, {"code": "B99000000", "type": "二级分类", "name": "其他建筑工程", "belong": "B", "children": []}]}, {"code": "C", "type": "一级分类", "name": "服务", "belong": null, "children": [{"code": "C01000000", "type": "二级分类", "name": "科学研究和试验开发", "belong": "C", "children": []}, {"code": "C02000000", "type": "二级分类", "name": "教育服务", "belong": "C", "children": []}, {"code": "C03000000", "type": "二级分类", "name": "就业服务", "belong": "C", "children": []}, {"code": "C04000000", "type": "二级分类", "name": "医疗卫生服务", "belong": "C", "children": []}, {"code": "C05000000", "type": "二级分类", "name": "社会服务", "belong": "C", "children": []}, {"code": "C06000000", "type": "二级分类", "name": "文化、体育、娱乐服务", "belong": "C", "children": []}, {"code": "C07000000", "type": "二级分类", "name": "生态环境保护和治理服务", "belong": "C", "children": []}, {"code": "C08000000", "type": "二级分类", "name": "能源的生产和分配服务", "belong": "C", "children": []}, {"code": "C09000000", "type": "二级分类", "name": "农林牧渔服务", "belong": "C", "children": []}, {"code": "C10000000", "type": "二级分类", "name": "采矿业和制造业服务", "belong": "C", "children": []}, {"code": "C11000000", "type": "二级分类", "name": "工程管理服务", "belong": "C", "children": []}, {"code": "C12000000", "type": "二级分类", "name": "水利管理服务", "belong": "C", "children": []}, {"code": "C13000000", "type": "二级分类", "name": "公共设施管理服务", "belong": "C", "children": []}, {"code": "C14000000", "type": "二级分类", "name": "公园和游览景区服务", "belong": "C", "children": []}, {"code": "C15000000", "type": "二级分类", "name": "交通运输和仓储服务", "belong": "C", "children": []}, {"code": "C16000000", "type": "二级分类", "name": "信息技术服务", "belong": "C", "children": []}, {"code": "C17000000", "type": "二级分类", "name": "电信和其他信息传输服务", "belong": "C", "children": []}, {"code": "C18000000", "type": "二级分类", "name": "金融服务", "belong": "C", "children": []}, {"code": "C19000000", "type": "二级分类", "name": "专业技术服务", "belong": "C", "children": []}, {"code": "C20000000", "type": "二级分类", "name": "鉴证咨询服务", "belong": "C", "children": []}, {"code": "C21000000", "type": "二级分类", "name": "房地产服务", "belong": "C", "children": []}, {"code": "C22000000", "type": "二级分类", "name": "会议、展览、住宿和餐饮服务", "belong": "C", "children": []}, {"code": "C23000000", "type": "二级分类", "name": "商务服务", "belong": "C", "children": []}, {"code": "C24000000", "type": "二级分类", "name": "政府和社会资本合作服务", "belong": "C", "children": []}, {"code": "C99000000", "type": "二级分类", "name": "其他服务", "belong": "C", "children": []}]}]}