123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245 |
- from fastapi import APIRouter, Request, Depends, HTTPException
- from sqlalchemy.exc import IntegrityError
- from fastapi.responses import JSONResponse
- from database import get_db
- from sqlalchemy.orm import Session
- from models import *
- import json
- import random
- from sqlalchemy import create_engine, select
- router = APIRouter()
- # @router.post('/create')
- # async def create_knowledge(request:Request,db:Session = Depends(get_db)):
- # data = await request.body()
- # body = data.decode(encoding='utf-8')
- # if len(body) > 0:
- # body = json.loads(body)
- # print(body)
- # random_10_digit_number = random.randint(1000000000, 9999999999)
- # # file_identifier = 'f'
- # reportId = 'ZJBG'+str(random_10_digit_number)
- # # file_identifier =
- # reportName = body["reportName"]
- # subject = body["subject"]
- # eventType = body["eventType"]
- # publishingUnit = body["publishingUnit"]
- # publishDate = body["publishDate"]
- # summary = body["summary"]
- #
- # notificationType = body["notificationType"]
- #
- # base_code = 'base'+str(random.randint(1000000000, 9999999999))
- #
- # fileNames = body["fileName"]
- # filePath = '/data/upload/mergefile/'
- #
- #
- #
- # konwledge = KnowledgeBase(
- # reportId=reportId,
- #
- # reportName=reportName,
- # subject=subject,
- # eventType=eventType,
- # publishingUnit=publishingUnit,
- # publishDate=publishDate,
- # summary = summary,
- # notificationType = notificationType,
- #
- # base_code = base_code
- # )
- # db.add(konwledge)
- #
- # for fileName in fileNames:
- # file_identifier='file'+str(random.randint(1000000000, 9999999999))
- # knowledge_file = KnowledgeFile(
- # file_identifier=file_identifier,
- # file_path=filePath,
- # file_name = fileName,
- # is_deleted = 0,
- # knowledge_base_code = base_code
- # )
- # db.add(knowledge_file)
- #
- # db.commit()
- # return {
- # "code":0,
- # "data":{
- # "reportId": reportId,
- # "status": "success",
- # "message": "总结报告创建成功"
- # }
- # }
- @router.post('/create')
- async def create_knowledge(request: Request, db: Session = Depends(get_db)):
- try:
- data = await request.body()
- body = json.loads(data.decode(encoding='utf-8'))
- # 验证必需的字段
- required_fields = ['reportName', 'subject', 'eventType', 'publishingUnit', 'publishDate', 'summary',
- 'notificationType', 'fileNames']
- missing_fields = [field for field in required_fields if field not in body]
- print('missing_fields',missing_fields)
- if missing_fields:
- raise HTTPException(status_code=401, detail=f"Missing required fields: {', '.join(missing_fields)}")
- # 生成随机的报告ID和基础知识代码
- random_10_digit_number = random.randint(1000000000, 9999999999)
- reportId = 'ZJBG' + str(random_10_digit_number)
- base_code = 'base' + str(random.randint(1000000000, 9999999999))
- # 从请求体中提取其他数据
- reportName = body["reportName"]
- subject = body["subject"]
- eventType = body["eventType"]
- publishingUnit = body["publishingUnit"]
- publishDate = body["publishDate"]
- summary = body["summary"]
- notificationType = body["notificationType"]
- fileNames = body["fileNames"] # 注意:这里假设它是列表
- # 创建 KnowledgeBase 实例
- konwledge = KnowledgeBase(
- reportId=reportId,
- reportName=reportName,
- subject=subject,
- eventType=eventType,
- publishingUnit=publishingUnit,
- publishDate=publishDate,
- summary=summary,
- notificationType=notificationType,
- base_code=base_code
- )
- db.add(konwledge)
- # 创建 KnowledgeFile 实例
- filePath = '/data/upload/mergefile/'
- for fileName in fileNames:
- file_identifier = 'file' + str(random.randint(1000000000, 9999999999))
- knowledge_file = KnowledgeFile(
- file_identifier=file_identifier,
- file_path=filePath + fileName, # 如果fileName是完整的路径,则可能不需要再次添加filePath
- file_name=fileName,
- is_deleted=0,
- knowledge_base_code=base_code
- )
- db.add(knowledge_file)
- db.commit()
- return {
- "code": 0,
- "data": {
- "reportId": reportId,
- "status": "success",
- "message": "总结报告创建成功"
- }
- }
- except json.JSONDecodeError:
- raise HTTPException(status_code=400, detail="Invalid JSON data")
- except IntegrityError as e:
- db.rollback()
- raise HTTPException(status_code=409, detail=f"Database error: {str(e)}")
- except Exception as e:
- db.rollback()
- print(e)
- raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
- @router.post('/select')
- @router.get('/select')
- async def select_knowledge(request: Request, db: Session = Depends(get_db)):
- # 尝试从请求体中解析 JSON 数据
- data = await request.json() # 注意:这里直接使用 request.json() 而不是 request.body()
- try:
- page = int(data.get('page', 1)) # 如果没有提供 page,则默认为 1
- size = int(data.get('size', 10)) # 如果没有提供 size,则默认为 10
- if size >100:
- size = 100
- except ValueError as e:
- # 如果转换失败,则抛出 HTTPException
- raise HTTPException(status_code=400, detail=f"Invalid pagination parameters: {e}")
- # 计算 offset
- offset = (page - 1) * size
- # 使用 ORM 查询并应用分页
- data = db.query(KnowledgeBase).offset(offset).limit(size).all()
- # 打印结果(可选,用于调试)
- # for i in data:
- # print(i)
- print(f"Returned {len(data)} results from page {page} with size {size}")
- # 计算总条数(注意:这可能会很慢,特别是对于大型数据集)
- total_count = db.query(func.count(KnowledgeBase.reportId)).scalar()
- # 计算总页数
- total_pages = (total_count // size) + (1 if total_count % size else 0)
- # 返回查询结果
- result = {
- "code": 0,
- 'msg': 'success',
- 'data': {
- 'pages': total_pages,
- 'total': total_count,
- "currentPage":page,
- "pageSize":size,
- "list": data
- }
- }
- return result
- @router.post('/detail')
- @router.get('/detail')
- async def get_knowledge_detail(request: Request, db: Session = Depends(get_db)):
- # 尝试从请求体中解析 JSON 数据
- data = await request.json()
- report_id = data.get('reportID')
- if not report_id:
- raise HTTPException(status_code=400, detail="Missing required parameter 'reportID'")
- # 查询 KnowledgeBase
- kb_entry = db.query(KnowledgeBase).filter(KnowledgeBase.reportId == report_id).first()
- if not kb_entry:
- raise HTTPException(status_code=404, detail="No knowledge base found for the given report ID")
- kf_entries = db.query(KnowledgeFile).filter(KnowledgeFile.knowledge_base_code == kb_entry.base_code).all()
- # 准备返回的数据
- result = {
- "code": 0,
- "msg": "success",
- "data": {
- "report_id": kb_entry.reportId,
- "reportName": kb_entry.reportName,
- "subject": kb_entry.subject,
- "eventType": kb_entry.eventType,
- "publishDate": kb_entry.publishDate,
- "publishingUnit": kb_entry.publishingUnit,
- "summary": kb_entry.summary,
- "notificationType": kb_entry.notificationType,
- # "knowledge_base_code": kb_entry.base_code,
- "file": [
- {
- "content": kf.file_name,
- "url": 'http://127.0.0.1:9988/api/file/download/'+kf.file_name
- } # 根据需要调整返回的字段
- for kf in kf_entries
- ]
- }
- }
- return result
|