__init__.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Request, Depends, Query, HTTPException, status
  4. from common.security import valid_access_token
  5. from sqlalchemy.orm import Session
  6. from sqlalchemy.sql import func
  7. from common.auth_user import *
  8. from sqlalchemy import text
  9. from pydantic import BaseModel
  10. from common.BigDataCenterAPI import *
  11. from database import get_db
  12. from typing import List
  13. from models import *
  14. from utils import *
  15. import json
  16. import traceback
  17. router = APIRouter()
  18. def convert_to_polygon(points):
  19. # 将点的列表转换为POLYGON格式的字符串
  20. polygon_str = "POLYGON(("
  21. for point in points:
  22. # 假设点的顺序是经度(x),纬度(y)
  23. polygon_str += f"{point['y']} {point['x']}, "
  24. # 移除最后一个逗号和空格,然后添加闭合点和结束括号
  25. polygon_str = polygon_str.rstrip(", ") + f", {points[0]['y']} {points[0]['x']}))"
  26. return polygon_str
  27. def count_town_village(location_list:list,db):
  28. town_count = 0
  29. town_list = []
  30. village_count = 0
  31. village_list = []
  32. result = []
  33. url = 'https://19.15.75.180:8581/GatewayMsg/http/api/proxy/invoke'
  34. service_code= 'YZT1685418808667'
  35. service_info = db.query(OneShareApiEntity).filter(OneShareApiEntity.servercode == service_code).first()
  36. signTime = str(GetTime() // 1000)
  37. nonce = GetNonce(5)
  38. sign = GetSign(signTime, nonce, service_info.passtoken)
  39. headers = {
  40. # 'Content-Type': 'application/json',
  41. 'x-tif-signature': sign,
  42. 'x-tif-timestamp': signTime,
  43. 'x-tif-nonce': nonce,
  44. 'x-tif-paasid': service_info.passid,
  45. 'x-tif-serviceId': service_code
  46. }
  47. response = requests.post(url=url, headers=headers, json=location_list, verify=False)
  48. if response.status_code==200:
  49. data_list = response.json()['data']
  50. for data in data_list:
  51. township = data['townshipCode']
  52. if township not in town_list:
  53. town_count+=1
  54. town_list.append(township)
  55. # result.append({'township':data['township'],"townshipCode":data['townshipCode'],"villages":[]})
  56. result.append({'township':data['township'],"townshipCode":data['townshipCode'],"village":'-',"villageCode":'-',"populationSize":0,"areaSize":0,"GDP":0})
  57. village = data['villageCode']
  58. if village not in village_list:
  59. village_count+=1
  60. village_list.append(village)
  61. # for town in result:
  62. # if town['townshipCode']==data['townshipCode']:
  63. # town["villages"].append({'village': data['village'], "villageCode": data['villageCode']})
  64. result.append({'township':data['township'],"townshipCode":data['townshipCode'],'village': data['village'], "villageCode": data['villageCode'],"populationSize":0,"areaSize":0,"GDP":0})
  65. return result,town_count,village_count
  66. def count_emergency_expert(location_list:list,db):
  67. location = convert_to_polygon(location_list)
  68. sql = text(f"""SELECT * FROM emergency_expert WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  69. return len(db.execute(sql).all())
  70. def count_emergency_management(location_list: list, db):
  71. location = convert_to_polygon(location_list)
  72. sql = text(f"""SELECT DISTINCT management_unit FROM `rescue_materia` WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  73. return len(db.execute(sql).all())
  74. class location_c(BaseModel):
  75. x:float
  76. y:float
  77. class mine(BaseModel):
  78. location : List=[]
  79. @router.post('/get_info')
  80. async def mine(request: Request,from_data:mine,body = Depends(remove_xss_json),db: Session = Depends(get_db)):
  81. try:
  82. # 验证必需的字段
  83. # required_fields = ['location','location_c']
  84. # missing_fields = [field for field in required_fields if field not in body]
  85. # if missing_fields:
  86. # raise HTTPException(status_code=401, detail=f"Missing required fields: {', '.join(missing_fields)}")
  87. # 行政镇、行政村数据
  88. town_village_data,town_count,village_count = count_town_village(from_data.location,db)
  89. emergency_expert_count = count_emergency_expert(from_data.location,db)
  90. emergency_management_count = count_emergency_management(from_data.location,db)
  91. return {
  92. "code": 200,
  93. "msg": "成功",
  94. "data": {
  95. "townVillageData":town_village_data,
  96. "townCount":town_count,
  97. "villageCount":village_count,
  98. "emergencyExpertCount":emergency_expert_count,
  99. "emergencyManagementCount":emergency_management_count
  100. }
  101. }
  102. except Exception as e:
  103. db.rollback()
  104. traceback.print_exc()
  105. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")