新增获取省市区接口

This commit is contained in:
18610128193
2026-06-17 15:29:52 +08:00
parent 15179cd2a4
commit 189aef6a82
4 changed files with 23576 additions and 1 deletions
+65 -1
View File
@@ -1,10 +1,13 @@
import json
from typing import Any, Optional
from typing import Any, Optional, Dict
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models.pre_test_template import PreTestTemplate
from app.utils.douyinApi import DouyinApi
from app.utils.area import parse_district_data, get_area_by_level, get_cached_area_data, fetch_and_cache_area_data
from app.dependencies import get_current_user, get_db
from app.models.user import User
@@ -292,3 +295,64 @@ async def delete_template(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"删除失败: {str(e)}",
)
@router.get(
"/getArea",
summary="获取行政区域信息",
description="获取指定级别的行政区域信息,支持一级、二级、三级区域,如果需要更新地区,执行:/api/pre-test-template/getArea?oauth_id=0019ecab9b8bc57d964&advertiser_id=1836693172153543",
)
async def get_template_area(
oauth_id: str = Query(None, description="授权ID选填,更新地区必填"),
advertiser_id: str = Query(default="1836693172153543", description="授权ID选填,更新地区必填"),
code: Optional[str] = Query("CN", description="行政区域编码,默认中国CN,选填"),
level: Optional[str] = Query("ONE_LEVEL", description="行政区域层级,可选值:ONE_LEVEL(获取省份)、TWO_LEVEL(市级)、THREE_LEVEL(区级)"),
parent_code: Optional[str] = Query(None, description="父级区域编码,获取二级时传一级编码,获取三级时传二级编码"),
) -> Any:
try:
# 1. 先检查缓存是否存在
area_list = get_cached_area_data()
# 2. 如果缓存不存在,调用接口获取数据并保存到缓存
if not area_list:
area_list = await fetch_and_cache_area_data(oauth_id, advertiser_id, code)
# 3. 根据 level 参数过滤区域
if level == "ONE_LEVEL":
result = get_area_by_level(area_list, "ONE_LEVEL")
elif level == "TWO_LEVEL":
result = get_area_by_level(area_list, "TWO_LEVEL", parent_code)
elif level == "THREE_LEVEL":
if not parent_code:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="获取三级区域需要提供二级区域编码(parent_code)",
)
result = get_area_by_level(area_list, "THREE_LEVEL", parent_code)
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"不支持的级别: {level}",
)
# 4. 转换为字典格式返回
result_dict = [area.to_dict() for area in result]
return {
"code": 0,
"message": "成功",
"data": result_dict,
}
except HTTPException:
raise
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"获取区域信息失败: {str(e)}",
)