baoyubo 8 месяцев назад
Родитель
Сommit
1e3e47edd3

+ 9 - 7
common/BigDataCenterAPI.py

@@ -1,8 +1,10 @@
 import requests,json,time,random,hashlib
 
+import string
+
 def api_request01(url,passid,serviceid,passtoken,jsons1,query,decoder='utf8'):
     signTime = str(GetTime()//1000)
-    nonce = GetNonce()
+    nonce = GetNonce(5)
     sign = GetSign(signTime,nonce,passtoken)
     headers = {
         'Content-Type':'application/json',
@@ -18,7 +20,7 @@ def api_request01(url,passid,serviceid,passtoken,jsons1,query,decoder='utf8'):
         "vender_id": GetKwargs(jsons1, 'vender_id'),
         "department_id": GetKwargs(jsons1, 'department_id'),
         "query_timestamp": query_timestamp,
-        "UID": GetNonce(),
+        "UID": GetNonce(5),
         "query": query,
         "audit_info": {
             "operator_id": GetKwargs(jsons1, 'operator_id'),
@@ -39,11 +41,11 @@ def api_request01(url,passid,serviceid,passtoken,jsons1,query,decoder='utf8'):
 def GetSign(signTime,nonce,passtoken):
     data = signTime+passtoken+nonce+signTime
     return hashlib.sha256(data.encode('utf-8')).hexdigest()
-def GetNonce():
-    reu = ''
-    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
-    for i in range(20):reu+=random.choice(base_str)
-    return reu
+def GetNonce(length):
+    characters = string.ascii_letters + string.digits
+    # 随机选择字符集的长度个字符
+    random_string = ''.join(random.choice(characters) for _ in range(length))
+    return random_string
 def GetTime():
     return int(time.time()*1000)
 def GetKwargs(dic,key):

+ 6 - 5
routers/api/OneShareProxyHandler/__init__.py

@@ -12,6 +12,7 @@ from pydantic import BaseModel
 from database import get_db
 from urllib import parse
 from models import *
+from utils import *
 import requests
 import hashlib
 import random
@@ -48,7 +49,7 @@ cache.ttl = 86400  # ttl(Time to Live) 以秒为单位
 
 @router.post('/proxyHandler/{city_code:path}/{service_code:path}')
 @router.get('/proxyHandler/{city_code:path}/{service_code:path}')
-async def mine(request: Request,db: Session = Depends(get_db)):
+async def mine(request: Request,body = Depends(remove_xss_json),db: Session = Depends(get_db)):
 
     target = str(request.url) # 获取接口地址
 
@@ -83,10 +84,10 @@ async def mine(request: Request,db: Session = Depends(get_db)):
     method = request.method
 
     # 获取请求体
-    body = await request.body()
-    body = body.decode(encoding='utf-8')
-    if len(body) > 0:
-        body = json.loads(body)
+    # body = await request.body()
+    # body = body.decode(encoding='utf-8')
+    # if len(body) > 0:
+    #     body = json.loads(body)
 
     # 获取默认params 1
     params_default = service_info.params_default

+ 3 - 1
routers/api/__init__.py

@@ -14,6 +14,7 @@ from . import videoResource
 from . import Knowledge
 from . import emergencyPlans
 from . import eventManagement
+from . import spatialAnalysis
 
 router = APIRouter()
 
@@ -29,4 +30,5 @@ router.include_router(videoResource.router, prefix="/videoResource")
 router.include_router(Knowledge.router, prefix="/knowledge")
 router.include_router(emergencyPlans.router, prefix="/emergency_plan")
 
-router.include_router(eventManagement.router, prefix="/event_management", tags=["事件管理"])
+router.include_router(eventManagement.router, prefix="/event_management", tags=["事件管理"])
+router.include_router(spatialAnalysis.router, prefix="/spatial_analysis", tags=["空间分析"])

+ 121 - 0
routers/api/spatialAnalysis/__init__.py

@@ -0,0 +1,121 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from fastapi import APIRouter, Request, Depends, Query, HTTPException, status
+from common.security import valid_access_token
+from sqlalchemy.orm import Session
+from sqlalchemy.sql import func
+from common.auth_user import *
+from pydantic import BaseModel
+from common.BigDataCenterAPI import *
+from database import get_db
+from typing import List
+from models import *
+from utils import *
+import json
+import traceback
+
+router = APIRouter()
+
+
+def convert_to_polygon(points):
+    # 将点的列表转换为POLYGON格式的字符串
+    polygon_str = "POLYGON(("
+    for point in points:
+        # 假设点的顺序是经度(x),纬度(y)
+        polygon_str += f"{point['y']} {point['x']}, "
+    # 移除最后一个逗号和空格,然后添加闭合点和结束括号
+    polygon_str = polygon_str.rstrip(", ") + f", {points[0]['y']} {points[0]['x']}))"
+    return polygon_str
+
+def count_town_village(location_list:list,db):
+    town_count = 0
+    town_list = []
+    village_count = 0
+    village_list = []
+    result = []
+
+    url = 'https://19.15.75.180:8581/GatewayMsg/http/api/proxy/invoke'
+    service_code= 'YZT1685418808667'
+    service_info = db.query(OneShareApiEntity).filter(OneShareApiEntity.servercode == service_code).first()
+
+    signTime = str(GetTime() // 1000)
+    nonce = GetNonce(5)
+    sign = GetSign(signTime, nonce, service_info.passtoken)
+    headers = {
+        # 'Content-Type': 'application/json',
+        'x-tif-signature': sign,
+        'x-tif-timestamp': signTime,
+        'x-tif-nonce': nonce,
+        'x-tif-paasid': service_info.passid,
+        'x-tif-serviceId': service_code
+    }
+    response = requests.post(url=url, headers=headers, json=location_list, verify=False)
+    if response.status_code==200:
+        data_list = response.json('data')
+        for data in data_list:
+            township = data['townshipCode']
+            if township not in town_list:
+                town_count+=1
+                result.append({'township':data['township'],"townshipCode":data['townshipCode'],"villages":[]})
+            village = data['villageCode']
+            if village not in village_list:
+                village_count+=1
+                for town in result:
+                    if town['townshipCode']==data['townshipCode']:
+                        town["villages"].append({'village': data['village'], "villageCode": data['villageCode']})
+
+
+    return result,town_count,village_count
+
+def count_emergency_expert(location_list:list,db):
+    location = convert_to_polygon(location_list)
+
+    sql = f"""SELECT * FROM emergency_expert WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))"""
+
+    return db.execute(sql).rowcount()
+
+def count_emergency_management(location_list: list, db):
+
+    location = convert_to_polygon(location_list)
+
+    sql = f"""SELECT DISTINCT management_unit FROM `rescue_materia`  WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))"""
+
+    return db.execute(sql).rowcount()
+
+class location(BaseModel):
+    x:float
+    y:float
+
+class mine(BaseModel):
+    location : List[location]=[]
+
+@router.post('/get_info')
+async def mine(request: Request,from_data:mine,body = Depends(remove_xss_json),db: Session = Depends(get_db)):
+    try:
+        # 验证必需的字段
+        required_fields = ['location']
+        missing_fields = [field for field in required_fields if field not in body]
+        if missing_fields:
+            raise HTTPException(status_code=401, detail=f"Missing required fields: {', '.join(missing_fields)}")
+
+        # 行政镇、行政村数据
+        town_village_data,town_count,village_count = count_town_village(from_data.location,db)
+        emergency_expert_count = count_emergency_expert(from_data.location,db)
+        emergency_management_count = count_emergency_management(from_data.location,db)
+
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data": {
+                "townVillageData":town_village_data,
+                "townCount":town_count,
+                "villageCount":village_count,
+                "emergencyExpertCount":emergency_expert_count,
+                "emergencyManagementCount":emergency_management_count
+            }
+        }
+    except Exception as e:
+        db.rollback()
+        traceback.print_exc()
+        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

+ 1 - 1
routers/prod_api/system/menu/__init__.py

@@ -397,7 +397,7 @@ class SysMuneUpdateForm(BaseModel):
     queryParam:str=None
     status:str = None
     visible:str = None
-@router.put('/update')
+@router.put('')
 async def update(
     request: Request,
     form_data: SysMuneUpdateForm,