__init__.py 4.4 KB

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