__init__.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Request, Depends, Query, HTTPException, status
  4. from fastapi.responses import JSONResponse,StreamingResponse
  5. from common.db import db_czrz
  6. from common.security import valid_access_token
  7. from sqlalchemy.orm import Session
  8. from sqlalchemy.sql import func
  9. from common.auth_user import *
  10. from sqlalchemy import text
  11. from pydantic import BaseModel
  12. from common.BigDataCenterAPI import *
  13. from database import get_db
  14. from typing import List
  15. from models import *
  16. from utils import *
  17. from utils.spatial import *
  18. import json
  19. import traceback
  20. from jobs.rainfall_conditions_job import get_stcd_data
  21. from datetime import datetime,timedelta
  22. from .rain_pits import router as rain_pits_router
  23. from .dzzh import router as dzzh_router
  24. from .chemical_company import router as chemical_company_router
  25. from .windspeed import router as windspeed_router
  26. router = APIRouter()
  27. router.include_router(rain_pits_router, prefix="/rain_pits")
  28. router.include_router(dzzh_router, prefix="/dzzh")
  29. router.include_router(chemical_company_router, prefix="/chemical_company")
  30. router.include_router(windspeed_router, prefix="/windspeed")
  31. @router.get("/info/{code}")
  32. async def get_pattern_info(
  33. code: str,
  34. db: Session = Depends(get_db)
  35. ):
  36. rainfulldata = get_stcd_data(code,12)
  37. update_time_list = []
  38. rainfall_history = []
  39. rainfall_future = []
  40. cumulative_rainfall = []
  41. for i in rainfulldata[::-1]:
  42. area_name = i['F3070220000034_000018002']
  43. update_time_list.append( datetime.strptime(i['F3070220000034_000018006'], "%Y-%m-%d %H:%M:%S"))
  44. create_time = datetime.strptime(i['F3070220000034_000018004'], "%Y-%m-%d %H:%M:%S")
  45. hour = create_time.strftime("%H")
  46. value = i['F3070220000034_000018005']
  47. rainfall_history.append({"hour":hour,"value":value})
  48. update_time_max = max(update_time_list).strftime("%Y-%m-%d %H:%M:%S")
  49. for t in range(1,13):
  50. future_time = create_time+ timedelta(hours=t)
  51. hour = future_time.strftime("%H")
  52. value = 0
  53. rainfall_future.append({"hour":hour,"value":value})
  54. rainfall = 0
  55. for cumulative in rainfall_history+rainfall_future:
  56. rainfall += cumulative['value']
  57. cumulative_rainfall.append({"hour":cumulative['hour'],"value":rainfall})
  58. return {
  59. "code": 200, "msg": "获取成功", "data":{"areaName":area_name,"updateTime":update_time_max,"rainfallHistory":rainfall_history,"rainfallFuture":rainfall_future,"cumulativeRainfall":cumulative_rainfall}
  60. }
  61. @router.get("/gdyl/info/{code}")
  62. async def get_pattern_info(
  63. code: str,
  64. db: Session = Depends(get_db)
  65. ):
  66. rainfulldata = get_stcd_data(code,25)
  67. update_time_list = []
  68. rainfall_history = []
  69. rainfall_future = []
  70. # cumulative_rainfall = []
  71. num = 24
  72. for i in rainfulldata[::-1]:
  73. area_name = i['F3070220000034_000018002']
  74. update_time_list.append( datetime.strptime(i['F3070220000034_000018006'], "%Y-%m-%d %H:%M:%S"))
  75. create_time = datetime.strptime(i['F3070220000034_000018004'], "%Y-%m-%d %H:%M:%S")
  76. # hour = create_time.strftime("%H")
  77. value = i['F3070220000034_000018005']
  78. if num in [24,12,6,3,1,0]:
  79. rainfall_history.append({"hour":-num,"value":value})
  80. num-=1
  81. update_time_max = max(update_time_list).strftime("%Y-%m-%d %H:%M:%S")
  82. # for t in range(72):
  83. # future_time = create_time+ timedelta(hours=t)
  84. # hour = future_time.strftime("%H")
  85. # value = 0
  86. rainfall_future.append({"hour":1,"value":0})
  87. rainfall_future.append({"hour":3,"value":0})
  88. rainfall_future.append({"hour":24,"value":1})
  89. rainfall_future.append({"hour":48,"value":4})
  90. rainfall_future.append({"hour":72,"value":2})
  91. rainfall = 0
  92. # for cumulative in rainfall_history+rainfall_future:
  93. # rainfall += cumulative['value']
  94. # cumulative_rainfall.append({"hour":cumulative['hour'],"value":rainfall})
  95. return {
  96. "code": 200, "msg": "获取成功", "data":{"areaName":area_name,"updateTime":update_time_max,"rainfallHistory":rainfall_history,"rainfallFuture":rainfall_future}#,"cumulativeRainfall":cumulative_rainfall}
  97. }
  98. @router.get('/get_rainfall_range/export')
  99. async def get_inspection_task_list(
  100. request: Request,
  101. sort: str = Query('desc'),
  102. timeOption: str = Query('24'),
  103. area: str = Query(''),
  104. township: str = Query(''),
  105. db: Session = Depends(get_db),
  106. auth_user: AuthUser = Depends(find_auth_user),
  107. user_id = Depends(valid_access_token)
  108. ):
  109. try:
  110. sql=f"""SELECT ROW_NUMBER() OVER ( ORDER BY T2.rainfall {sort}) AS `序号`,T1.area as `区县`,T1.township as `镇街`,T1.address as `站点地址`,T1.area_name as `站点名称`,T2.rainfall as `雨量`,T1.`code` as `站点编号` FROM sharedb.govdata_real_time_address T1 LEFT JOIN (select `latest_data`.`code` AS `code`,sum(`latest_data`.`rainfall`) AS `rainfall` from (select `govdata_rain_data_info`.`code` AS `code`,`govdata_rain_data_info`.`area_name` AS `area_name`,`govdata_rain_data_info`.`address` AS `address`,`govdata_rain_data_info`.`create_time` AS `create_time`,`govdata_rain_data_info`.`rainfall` AS `rainfall`,`govdata_rain_data_info`.`update_time` AS `update_time`,row_number() OVER (PARTITION BY `govdata_rain_data_info`.`code` ORDER BY `govdata_rain_data_info`.`create_time` desc ) AS `rn` from sharedb.`govdata_rain_data_info`) `latest_data` where ((`latest_data`.`rn` <= '{timeOption}') and `latest_data`.`code` in (select `govdata_real_time_address`.`code` from sharedb.`govdata_real_time_address`)) group by `latest_data`.`code` order by `rainfall` desc) T2 on T1.code=T2.code where CASE
  111. WHEN '{area}'<>'' THEN
  112. T1.area='{area}'
  113. ELSE
  114. 1=1
  115. END and CASE
  116. WHEN '{township}'<>'' THEN
  117. T1.township='{township}'
  118. ELSE
  119. 1=1
  120. END and T2.rainfall>0 ORDER BY T2.rainfall {sort}"""
  121. da = db.execute(sql).fetchall()
  122. outlist = [dict(row) for row in da]
  123. # 返回结果
  124. import pandas as pd
  125. from io import BytesIO
  126. # 将查询结果转换为 DataFrame
  127. df = pd.DataFrame(outlist)
  128. # 将 DataFrame 导出为 Excel 文件
  129. output = BytesIO()
  130. with pd.ExcelWriter(output, engine='openpyxl') as writer:
  131. df.to_excel(writer, index=False)
  132. # 设置响应头
  133. output.seek(0)
  134. from urllib.parse import quote
  135. encoded_filename = f'雨量排行榜导出{datetime.now().strftime("%Y%m%d%H%mi%s")}.xlsx'
  136. encoded_filename = quote(encoded_filename, encoding='utf-8')
  137. headers = {
  138. 'Content-Disposition': f'attachment; filename*=UTF-8\'\'{encoded_filename}',
  139. 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  140. }
  141. db_czrz.log(db, auth_user, "雨量监测", f"雨量排行榜导出数据成功", request.client.host)
  142. # 返回文件流
  143. return StreamingResponse(output, headers=headers)
  144. except Exception as e:
  145. # 处理异常
  146. traceback.print_exc()
  147. return JSONResponse(status_code=500, content={"code": 500, "msg": f"Internal server error: {str(e)}"})
  148. @router.get('/get_rainfall_range')
  149. async def get_inspection_task_list(
  150. request: Request,
  151. sort: str = Query('desc'),
  152. history_time: int = Query(None),
  153. future_time: int = Query(None),
  154. area: str = Query(''),
  155. township: str = Query(''),
  156. db: Session = Depends(get_db),
  157. auth_user: AuthUser = Depends(find_auth_user),
  158. user_id = Depends(valid_access_token)
  159. ):
  160. try:
  161. if history_time:
  162. sql=f"""SELECT ROW_NUMBER() OVER ( ORDER BY T2.rainfall {sort}) AS `row`,T1.area as `area`,T1.township as `township`,T1.address as `address`,T1.area_name as `area_name`,T2.rainfall as `rainfall`,T1.`code` as `code` FROM sharedb.govdata_real_time_address T1 LEFT JOIN (select `latest_data`.`code` AS `code`,sum(`latest_data`.`rainfall`) AS `rainfall` from (select `govdata_rain_data_info`.`code` AS `code`,`govdata_rain_data_info`.`area_name` AS `area_name`,`govdata_rain_data_info`.`address` AS `address`,`govdata_rain_data_info`.`create_time` AS `create_time`,`govdata_rain_data_info`.`rainfall` AS `rainfall`,`govdata_rain_data_info`.`update_time` AS `update_time`,row_number() OVER (PARTITION BY `govdata_rain_data_info`.`code` ORDER BY `govdata_rain_data_info`.`create_time` desc ) AS `rn` from sharedb.`govdata_rain_data_info`) `latest_data` where ((`latest_data`.`rn` <= '{history_time}') and `latest_data`.`code` in (select `govdata_real_time_address`.`code` from sharedb.`govdata_real_time_address`)) group by `latest_data`.`code` order by `rainfall` desc) T2 on T1.code=T2.code where CASE
  163. WHEN '{area}'<>'' THEN
  164. T1.area='{area}'
  165. ELSE
  166. 1=1
  167. END and CASE
  168. WHEN '{township}'<>'' THEN
  169. T1.township='{township}'
  170. ELSE
  171. 1=1
  172. END and T2.rainfall>0 ORDER BY T2.rainfall {sort}"""
  173. da = db.execute(sql).fetchall()
  174. outlist = [dict(row) for row in da]
  175. # 返回结果
  176. return { "code": 200,
  177. "msg": "操作成功",
  178. "data": outlist,}
  179. if future_time:
  180. return {"code": 200,
  181. "msg": "操作成功",
  182. "data": [{"row":1,"area":"茂名市","township":"茂南区","address":"暂无","area_name":"茂南","rainfall":0,"code":"1234"}]}
  183. if history_time is None and future_time is None:
  184. return {"code": 200,
  185. "msg": "操作成功",
  186. "data": []}
  187. except Exception as e:
  188. # 处理异常
  189. traceback.print_exc()
  190. return JSONResponse(status_code=500, content={"code": 500, "msg": f"Internal server error: {str(e)}"})