123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- from fastapi import APIRouter, Request, Depends, Query, HTTPException, status,WebSocket,WebSocketDisconnect
- from common.security import valid_access_token,valid_websocket_token
- from fastapi.responses import JSONResponse
- from sqlalchemy.orm import Session
- from sqlalchemy.sql import func
- from common.auth_user import *
- from sqlalchemy import text
- from pydantic import BaseModel
- from common.BigDataCenterAPI import *
- from database import get_db
- from typing import List
- from models import *
- from utils import *
- from utils.spatial import *
- from utils.ry_system_util import *
- from common.websocketManager import *
- from openpyxl import load_workbook
- from PIL import Image
- import io
- import json
- import xlrd,os
- import traceback
- router = APIRouter()
- def classification_id_get_classification_info(db,id):
- query = db.query(TpPatternClassification)
- query = query.filter_by(classification_id = id,del_flag = '0')
- return query.first()
- def template_id_get_classification_list(db,id):
- query = db.query(TpPatternClassification)
- query = query.filter_by(template_id = id,del_flag = '0')
- query = query.order_by(TpPatternClassification.order_num.asc())
- return query.all()
- def template_id_get_template_info(db,id):
- query = db.query(TpPatternTemplate)
- query = query.filter_by(template_id = id,del_flag = '0')
- return query.first()
- def read_save_excel_img(file_path):
- wb = load_workbook(file_path)
- ws = wb.active
- data={}
- for drawing in ws._images:
- img_bytes = drawing._data()
- anchor = drawing.anchor
- # 锚点给出的是“起始行列”和“终止行列”
- col0, row0 = anchor._from.col, anchor._from.row
- img = Image.open(io.BytesIO(img_bytes))
- w, h = img.size # 像素宽高
- # print(f'第1张图片:宽={w}px, 高={h}px')
- name = new_guid()
- img.save(f'{name}.png')
- data[f'{col0}-{row0}']={"size":[h, w],"image":f'{name}.png'}
- return data
- @router.post('/createImport')
- async def create_contact(
- request: Request,
- db: Session = Depends(get_db),
- body=Depends(remove_xss_json),
- auth_user: AuthUser = Depends(find_auth_user),
- user_id=Depends(valid_access_token)
- ):
- try:
- # 提取请求数据
- filename = body['filename']
- # file_name_desc = body['file_name_desc']
- template_id = body['template_id']
- if len(filename) == 0:
- raise Exception()
- file_path = f'/data/upload/mergefile/uploads/{filename}'
- # 检查文件是否存在
- if not os.path.isfile(file_path):
- return JSONResponse(status_code=404, content={
- 'errcode': 404,
- 'errmsg': f'{filename}不存在'
- })
- msg = '成功'
- code =200
- try:
- book = xlrd.open_workbook(file_path)
- sheet = book.sheet_by_index(0)
- img_list = read_save_excel_img(file_path)
- if sheet.nrows-1 != len(img_list):
- msg = f'\n文件图片缺失,请核实图片个数是否为 {sheet.nrows-1}'
- code = 500
- return JSONResponse(status_code=code, content={
- "code": code,
- "msg": msg,
- "data": None
- })
- except Exception as e:
- traceback.print_exc()
- msg = f'\n文件打开失败,请核实文件格式为xlsx/xlx>{str(e)}'
- code = 500
- return JSONResponse(status_code=code, content={
- "code": code,
- "msg": msg,
- "data": None
- })
- data = []
- import_status = True
- for row in range(1, sheet.nrows):
- name = sheet.cell(row, 0).value
- if name == '' or name==0:
- import_status = False
- msg = f'\n行<{row + 1}>分类名称不能为空<{name}>'
- code = 500
- value = sheet.cell(row, 1).value
- if value == '':
- import_status = False
- msg = f'\n行<{row + 1}>分类值不能为空<{value}>'
- code = 500
- try:
- img_data=img_list[f'2-{row}']
- except:
- import_status = False
- msg = f'\n行<{row + 1}>图片不能为空<{value}>'
- code = 500
- return JSONResponse(status_code=code, content={
- "code": code,
- "msg": msg,
- "data": None
- })
- new_classification = TpPatternClassification(
- classification_id=new_guid(),
- template_id=template_id,
- name=body['name'],
- value=body['value'],
- order_num=0,
- visible='1',
- image=img_data['image'],
- icon=body['value'],
- size=img_data['size'],
- create_by=user_id
- )
- data.append(new_classification)
- if import_status:
- db.add_all(data)
- db.commit()
- except Exception as e:
- traceback.print_exc()
- # 处理异常
- db.rollback()
- code = 500
- msg = str(e)
- return JSONResponse(status_code=code, content={
- "code": code,
- "msg": msg,
- "data": None
- })
- @router.post("/create")
- async def create_pattern(
- user_id=Depends(valid_access_token),
- body = Depends(remove_xss_json),
- db: Session = Depends(get_db)
- ):
- try:
- if 'order_num' in body:
- order_num=body['order_num']
- else:
- info = db.query(func.max(TpPatternClassification.order_num).label('max_value')).filter_by(template_id=body['template_id']).first()
- if info.max_value:
- order_num=info.max_value+1
- else:
- order_num=1
- if 'visible'in body:
- visible=body['visible']
- else:
- visible='1'
- new_classification = TpPatternClassification(
- classification_id=new_guid(),
- template_id=body['template_id'],
- name=body['name'],
- value=body['value'],
- order_num = order_num,
- visible=visible,
- image=body['image'],
- icon=body['icon'],
- size=body['size'],
- create_by = user_id
- )
- db.add(new_classification)
- db.commit()
- return {"code": 200, "msg": "创建成功", "data": None}
- except Exception as e:
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
- @router.put("/update/{id}")
- async def update_classification(
- id :str ,
- user_id=Depends(valid_access_token),
- body=Depends(remove_xss_json),
- db: Session = Depends(get_db)
- ):
- try:
- update_classification = classification_id_get_classification_info(db,id)
- if not update_classification:
- return JSONResponse(status_code=404,content={"code":404,"msg":"classification not found"})
- update_classification.template_id = body['template_id']
- update_classification.name = body['name']
- update_classification.value=body['value']
- update_classification.order_num=body['order_num']
- update_classification.visible=body['visible']
- update_classification.image=body['image']
- update_classification.icon=body['icon']
- update_classification.size=body['size']
- update_classification.update_by = user_id
- db.commit()
- return {"code": 200, "msg": "更新成功"}
- except Exception as e:
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
- @router.get("/info/{id}")
- async def get_pattern_info(
- id: str,
- db: Session = Depends(get_db)
- ):
- try:
- info = classification_id_get_classification_info(db,id)
- if not info:
- return JSONResponse(status_code=404,content={"code":404,"msg":"classification not found"})
- template_info = template_id_get_template_info(db,info.template_id)
- data = {"classification_id": info.classification_id,
- "template_id": info.template_id,
- "template_name":template_info.name,
- "name": info.name,
- "value": info.value,
- "order_num": info.order_num,
- "visible": info.visible,
- "image": info.image,
- "icon": info.icon,
- "size": info.size,
- "create_time": info.create_time}
- return {"code": 200, "msg": "获取成功", "data": data}
- except Exception as e:
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
- @router.get("/list")
- async def get_pattern_list(
- name: str = Query(None, description='名称'),
- page: int = Query(1, gt=0, description='页码'),
- pageSize: int = Query(None, gt=0, description='每页条目数量'),
- db: Session = Depends(get_db)
- ):
- try:
- query = db.query(TpPatternClassification)
- query = query.filter_by(del_flag='0')
- if name:
- query = query.filter(TpPatternClassification.name.like(f'%{name}%'))
- total_items = query.count()
- # 排序
- if pageSize is None:
- pageSize=total_items
- query = query.order_by(TpPatternClassification.order_num.asc())
- # 执行分页查询
- lists = query.offset((page - 1) * pageSize).limit(pageSize).all()
- data = [ ]
- for info in lists:
- template_info = template_id_get_template_info(db, info.template_id)
- data.append({"classification_id": info.classification_id,
- "template_id": info.template_id,
- "template_name":template_info.name,
- "name": info.name,
- "value": info.value,
- "order_num": info.order_num,
- "visible": info.visible,
- "image": info.image,
- "icon": info.icon,
- "size": info.size,
- "create_time": info.create_time})
- return {"code": 200, "msg": "查询成功", "data": data,
- "total": total_items,
- "page": page,
- "pageSize": pageSize,
- "totalPages": (total_items + pageSize - 1) // pageSize
- }
- except Exception as e:
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
- @router.delete("/delete/{id}")
- async def delete_pattern(
- id: str,
- db: Session = Depends(get_db)
- ):
- try:
- # 检查图案是否存在
- info = classification_id_get_classification_info(db, id)
- if not info:
- return JSONResponse(status_code=404, content={"code": 404, "msg": "classification not found"})
- info.del_flag='2'
- db.commit()
- return {"code": 200, "msg": "删除成功"}
- except Exception as e:
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
- @router.put('/changeVisible')
- async def change_classification_visible(
- db: Session = Depends(get_db),
- body=Depends(remove_xss_json),
- user_id=Depends(valid_access_token)
- ):
- try:
- classification_id = body['classification_id']
- visible = body['visible']
- info = classification_id_get_classification_info(db, classification_id)
- if not info:
- return JSONResponse(status_code=404, content={"code": 404, "msg": "classification not found"})
- info.visible= visible
- info.update_by=user_id
- db.commit()
- return {
- "code": 200,
- "msg": "操作成功"
- }
- except Exception as e:
- # 处理异常
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=str(e))
- @router.get("/templateTree")
- async def get_pattern_list(
- visible: str = Query(None, description='是否显示'),
- # page: int = Query(1, gt=0, description='页码'),
- # pageSize: int = Query(None, gt=0, description='每页条目数量'),
- db: Session = Depends(get_db)
- ):
- try:
- query = db.query(TpPatternTemplate)
- query = query.filter_by(del_flag='0')
- if visible is not None:
- query = query.filter_by(visible=visible)
- # if name:
- # query = query.filter(TpPatternTemplate.name.like(f'%{name}%'))
- # total_items = query.count()
- # # 排序
- # if pageSize is None:
- # pageSize=total_items
- query = query.order_by(TpPatternTemplate.order_num.asc())
- # 执行分页查询
- lists = query.all() # .offset((page - 1) * pageSize).limit(pageSize)
- data = []
- for info in lists:
- # print(1111)
- query1 = db.query(TpPatternClassification)
- query1 = query1.filter_by(template_id=info.template_id, del_flag='0')
- if visible is not None:
- query1 = query1.filter_by(visible=visible)
- query1 = query1.order_by(TpPatternClassification.order_num.asc())
- classification_list = query1.all()
- # =template_id_get_classification_list(db,info.template_id)
- template_info = {"template_id": info.template_id,
- "name": info.name,
- "value": info.value,
- "order_num": info.order_num,
- "visible": info.visible,
- "create_time": info.create_time}
- if classification_list:
- template_info['children']=[{"classification_id": classification.classification_id,
- "name": classification.name,
- "value": classification.value,
- "order_num": classification.order_num,
- "visible": classification.visible,
- "image": classification.image,
- "icon": classification.icon,
- "size": classification.size,
- "create_time": classification.create_time} for classification in classification_list]
- data.append(template_info)
- return {"code": 200, "msg": "查询成功", "data": data}
- except Exception as e:
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|