__init__.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. from fastapi import APIRouter, Request, Depends, HTTPException
  2. from sqlalchemy.exc import IntegrityError
  3. from fastapi.responses import JSONResponse
  4. from database import get_db
  5. from sqlalchemy.orm import Session
  6. from models import *
  7. import json
  8. import random
  9. from sqlalchemy import create_engine, select
  10. router = APIRouter()
  11. # @router.post('/create')
  12. # async def create_knowledge(request:Request,db:Session = Depends(get_db)):
  13. # data = await request.body()
  14. # body = data.decode(encoding='utf-8')
  15. # if len(body) > 0:
  16. # body = json.loads(body)
  17. # print(body)
  18. # random_10_digit_number = random.randint(1000000000, 9999999999)
  19. # # file_identifier = 'f'
  20. # reportId = 'ZJBG'+str(random_10_digit_number)
  21. # # file_identifier =
  22. # reportName = body["reportName"]
  23. # subject = body["subject"]
  24. # eventType = body["eventType"]
  25. # publishingUnit = body["publishingUnit"]
  26. # publishDate = body["publishDate"]
  27. # summary = body["summary"]
  28. #
  29. # notificationType = body["notificationType"]
  30. #
  31. # base_code = 'base'+str(random.randint(1000000000, 9999999999))
  32. #
  33. # fileNames = body["fileName"]
  34. # filePath = '/data/upload/mergefile/'
  35. #
  36. #
  37. #
  38. # konwledge = KnowledgeBase(
  39. # reportId=reportId,
  40. #
  41. # reportName=reportName,
  42. # subject=subject,
  43. # eventType=eventType,
  44. # publishingUnit=publishingUnit,
  45. # publishDate=publishDate,
  46. # summary = summary,
  47. # notificationType = notificationType,
  48. #
  49. # base_code = base_code
  50. # )
  51. # db.add(konwledge)
  52. #
  53. # for fileName in fileNames:
  54. # file_identifier='file'+str(random.randint(1000000000, 9999999999))
  55. # knowledge_file = KnowledgeFile(
  56. # file_identifier=file_identifier,
  57. # file_path=filePath,
  58. # file_name = fileName,
  59. # is_deleted = 0,
  60. # knowledge_base_code = base_code
  61. # )
  62. # db.add(knowledge_file)
  63. #
  64. # db.commit()
  65. # return {
  66. # "code":0,
  67. # "data":{
  68. # "reportId": reportId,
  69. # "status": "success",
  70. # "message": "总结报告创建成功"
  71. # }
  72. # }
  73. @router.post('/create')
  74. async def create_knowledge(request: Request, db: Session = Depends(get_db)):
  75. try:
  76. data = await request.body()
  77. body = json.loads(data.decode(encoding='utf-8'))
  78. # 验证必需的字段
  79. required_fields = ['reportName', 'subject', 'eventType', 'publishingUnit', 'publishDate', 'summary',
  80. 'fileNames']
  81. missing_fields = [field for field in required_fields if field not in body]
  82. print('missing_fields',missing_fields)
  83. if missing_fields:
  84. raise HTTPException(status_code=401, detail=f"Missing required fields: {', '.join(missing_fields)}")
  85. # 生成随机的报告ID和基础知识代码
  86. random_10_digit_number = random.randint(1000000000, 9999999999)
  87. reportId = 'ZJBG' + str(random_10_digit_number)
  88. base_code = 'base' + str(random.randint(1000000000, 9999999999))
  89. # 从请求体中提取其他数据
  90. reportName = body["reportName"]
  91. subject = body["subject"]
  92. eventType = body["eventType"]
  93. publishingUnit = body["publishingUnit"]
  94. publishDate = body["publishDate"]
  95. summary = body["summary"]
  96. # notificationType = body["notificationType"]
  97. notificationType = "总结报告"
  98. fileNames = body["fileNames"] # 注意:这里假设它是列表
  99. # 创建 KnowledgeBase 实例
  100. konwledge = KnowledgeBase(
  101. reportId=reportId,
  102. reportName=reportName,
  103. subject=subject,
  104. eventType=eventType,
  105. publishingUnit=publishingUnit,
  106. publishDate=publishDate,
  107. summary=summary,
  108. notificationType=notificationType,
  109. base_code=base_code
  110. )
  111. db.add(konwledge)
  112. # 创建 KnowledgeFile 实例
  113. filePath = '/data/upload/mergefile/'
  114. for fileName in fileNames:
  115. file_identifier = 'file' + str(random.randint(1000000000, 9999999999))
  116. knowledge_file = KnowledgeFile(
  117. file_identifier=file_identifier,
  118. file_path=filePath + fileName, # 如果fileName是完整的路径,则可能不需要再次添加filePath
  119. file_name=fileName,
  120. is_deleted=0,
  121. knowledge_base_code=base_code
  122. )
  123. db.add(knowledge_file)
  124. db.commit()
  125. return {
  126. "code": 200,
  127. "data": {
  128. "reportId": reportId,
  129. "status": "success",
  130. "message": "总结报告创建成功"
  131. }
  132. }
  133. except json.JSONDecodeError:
  134. raise HTTPException(status_code=400, detail="Invalid JSON data")
  135. except IntegrityError as e:
  136. db.rollback()
  137. raise HTTPException(status_code=409, detail=f"Database error: {str(e)}")
  138. except Exception as e:
  139. db.rollback()
  140. print(e)
  141. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  142. @router.post('/select')
  143. @router.get('/select')
  144. async def select_knowledge(request: Request, db: Session = Depends(get_db)):
  145. # 尝试从请求体中解析 JSON 数据
  146. data = await request.json() # 注意:这里直接使用 request.json() 而不是 request.body()
  147. try:
  148. page = int(data.get('page', 1)) # 如果没有提供 page,则默认为 1
  149. size = int(data.get('size', 10)) # 如果没有提供 size,则默认为 10
  150. if size >100:
  151. size = 100
  152. except ValueError as e:
  153. # 如果转换失败,则抛出 HTTPException
  154. raise HTTPException(status_code=400, detail=f"Invalid pagination parameters: {e}")
  155. # 计算 offset
  156. offset = (page - 1) * size
  157. # 使用 ORM 查询并应用分页
  158. data = db.query(KnowledgeBase).offset(offset).limit(size).all()
  159. # 打印结果(可选,用于调试)
  160. # for i in data:
  161. # print(i)
  162. print(f"Returned {len(data)} results from page {page} with size {size}")
  163. # 计算总条数(注意:这可能会很慢,特别是对于大型数据集)
  164. total_count = db.query(func.count(KnowledgeBase.reportId)).scalar()
  165. # 计算总页数
  166. total_pages = (total_count // size) + (1 if total_count % size else 0)
  167. # 返回查询结果
  168. result = {
  169. "code": 200,
  170. 'msg': 'success',
  171. 'data': {
  172. 'pages': total_pages,
  173. 'total': total_count,
  174. "currentPage":page,
  175. "pageSize":size,
  176. "list": data
  177. }
  178. }
  179. return result
  180. @router.post('/detail')
  181. @router.get('/detail')
  182. async def get_knowledge_detail(request: Request, db: Session = Depends(get_db)):
  183. # 尝试从请求体中解析 JSON 数据
  184. data = await request.json()
  185. report_id = data.get('reportID')
  186. if not report_id:
  187. raise HTTPException(status_code=400, detail="Missing required parameter 'reportID'")
  188. # 查询 KnowledgeBase
  189. kb_entry = db.query(KnowledgeBase).filter(KnowledgeBase.reportId == report_id).first()
  190. if not kb_entry:
  191. raise HTTPException(status_code=404, detail="No knowledge base found for the given report ID")
  192. kf_entries = db.query(KnowledgeFile).filter(KnowledgeFile.knowledge_base_code == kb_entry.base_code).all()
  193. # 准备返回的数据
  194. result = {
  195. "code": 200,
  196. "msg": "success",
  197. "data": {
  198. "report_id": kb_entry.reportId,
  199. "reportName": kb_entry.reportName,
  200. "subject": kb_entry.subject,
  201. "eventType": kb_entry.eventType,
  202. "publishDate": kb_entry.publishDate,
  203. "publishingUnit": kb_entry.publishingUnit,
  204. "summary": kb_entry.summary,
  205. "notificationType": kb_entry.notificationType,
  206. # "knowledge_base_code": kb_entry.base_code,
  207. "file": [
  208. {
  209. "content": kf.file_name,
  210. "url": 'http://127.0.0.1:9988/api/file/download/'+kf.file_name
  211. } # 根据需要调整返回的字段
  212. for kf in kf_entries
  213. ]
  214. }
  215. }
  216. return result