__init__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. from fastapi import APIRouter, Request, Depends, HTTPException, Query
  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. from typing import Optional
  11. from utils.StripTagsHTMLParser import *
  12. router = APIRouter()
  13. @router.post('/create')
  14. async def create_event(request: Request, db: Session = Depends(get_db), body = Depends(remove_xss_json)):
  15. try:
  16. # 验证必需的字段
  17. required_fields = ['eventTitle', 'eventType', 'eventLevel', 'eventStatus', 'eventTime', 'reportTime',
  18. 'deaths', 'injuries', "missing", "eventSource", "longitude", "latitude", "eventDescription", "address"]
  19. missing_fields = [field for field in required_fields if field not in body]
  20. print('missing_fields',missing_fields)
  21. if missing_fields:
  22. raise HTTPException(status_code=401, detail=f"Missing required fields: {', '.join(missing_fields)}")
  23. random_10_digit_number = random.randint(1000000000, 9999999999)
  24. eventId = 'YJSJ' + str(random_10_digit_number)
  25. username = "..."
  26. # 创建 事件 实例
  27. incident_base = Incident(
  28. code = eventId,
  29. title = body["eventTitle"],
  30. incident_type = body["eventType"],
  31. incident_level = body["eventLevel"],
  32. status = body["eventStatus"],
  33. occurrence_time = body["eventTime"],
  34. report_time = body["reportTime"],
  35. fatalities = body["deaths"],
  36. injuries = body["injuries"],
  37. missing = body["missing"],
  38. source = body["eventSource"],
  39. location = body["address"],
  40. longitude = body["longitude"],
  41. latitude = body["latitude"],
  42. summary = body["eventDescription"],
  43. recorded_by = username,
  44. del_flag = "0"
  45. )
  46. db.add(incident_base)
  47. return {
  48. "code": 200,
  49. "msg": "事件创建成功",
  50. "status": "success",
  51. "data": eventId
  52. }
  53. except json.JSONDecodeError:
  54. raise HTTPException(status_code=400, detail="Invalid JSON data")
  55. except IntegrityError as e:
  56. db.rollback()
  57. raise HTTPException(status_code=409, detail=f"Database error: {str(e)}")
  58. except Exception as e:
  59. db.rollback()
  60. print(e)
  61. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  62. @router.get('/list')
  63. async def get_event_list(
  64. eventType: str = Query(None, description='事件类型的字典键值'),
  65. eventLevel: str = Query(None, description='事件等级的字典键值'),
  66. eventStatus: str = Query(None, description='事件状态的字典键值'),
  67. eventTime: str = Query(None, description='事发时间'),
  68. regionCode: str = Query(None, description='行政区划代码'),
  69. searchTerm: str = Query(None, description='根据事件标题或描述中的关键字进行模糊搜索'),
  70. sortBy: str = Query(None, description='排序字段'),
  71. sortOrder: str = Query("asc", description='排序方式'),
  72. page: int = Query(1, gt=0, description='页码'),
  73. pageSize: int = Query(10, gt=0, description='pageSize'),
  74. db: Session = Depends(get_db)
  75. ):
  76. try:
  77. # 构建查询
  78. query = db.query(Incident)
  79. query = query.filter(Incident.del_flag != '2')
  80. # 应用查询条件
  81. # 计算总条目数
  82. total_items = query.count()
  83. # 执行分页查询
  84. rows = query.offset((page - 1) * pageSize).limit(pageSize).all()
  85. data = [
  86. {
  87. "eventId": row.code,
  88. "eventTitle": row.title,
  89. "eventType": row.incident_type,
  90. "eventLevel": row.incident_level,
  91. "eventStatus": row.status,
  92. "latitude": row.latitude,
  93. "longitude": row.longitude,
  94. "address": row.location,
  95. "eventTime": row.occurrence_time.strftime("%Y-%m-%d %H:%M")
  96. }
  97. for row in rows
  98. ]
  99. # 返回结果
  100. return {
  101. "code": 200,
  102. "msg": "成功",
  103. "data": data,
  104. "total": total_items,
  105. "currentPage": page,
  106. "pageSize": pageSize,
  107. "totalPages": (total_items + pageSize - 1) // pageSize
  108. }
  109. except Exception as e:
  110. # 处理异常
  111. raise HTTPException(status_code=500, detail=str(e))
  112. @router.get('/detail')
  113. async def get_event_detail(
  114. request: Request,
  115. eventId: str,
  116. db: Session = Depends(get_db)):
  117. try:
  118. # 构建查询
  119. query = db.query(Incident)
  120. query = query.filter(Incident.code == eventId)
  121. # 执行查询
  122. row = query.first()
  123. if row is not None:
  124. eventTimeline = []
  125. commandRecords = []
  126. return {
  127. "code": 200,
  128. "msg": "查询成功",
  129. "data": {
  130. "eventId": row.code,
  131. "eventTitle": row.title,
  132. "eventType": row.incident_type,
  133. "eventLevel": row.incident_level,
  134. "eventStatus": row.status,
  135. "eventSource": row.source,
  136. "eventTime": row.occurrence_time.strftime("%Y-%m-%d %H:%M"),
  137. "reportTime": row.report_time.strftime("%Y-%m-%d %H:%M"),
  138. "deaths": row.fatalities,
  139. "injuries": row.injuries,
  140. "missing": row.missing,
  141. "reportedBy": row.recorded_by,
  142. "contact": row.contact,
  143. "eventDescription": row.summary,
  144. "latitude": row.latitude,
  145. "longitude": row.longitude,
  146. "address": row.location,
  147. "eventTimeline": eventTimeline,
  148. "commandRecords": commandRecords
  149. }
  150. }
  151. else:
  152. return {
  153. "code": 500,
  154. "msg": "查询失败"
  155. }
  156. except Exception as e:
  157. # 处理异常
  158. raise HTTPException(status_code=500, detail=str(e))
  159. @router.post('/close')
  160. async def close_event(
  161. request: Request,
  162. db: Session = Depends(get_db),
  163. body = Depends(remove_xss_json)):
  164. try:
  165. # 验证必需的字段
  166. required_fields = ['eventId', 'eventStatus', 'deaths', 'injuries', 'missing', 'fileNames']
  167. missing_fields = [field for field in required_fields if field not in body]
  168. print('missing_fields', missing_fields)
  169. if missing_fields:
  170. raise HTTPException(status_code=401, detail=f"Missing required fields: {', '.join(missing_fields)}")
  171. return {
  172. "code": 200,
  173. "msg": "总结报告创建成功"
  174. }
  175. except Exception as e:
  176. # 处理异常
  177. raise HTTPException(status_code=500, detail=str(e))