init
This commit is contained in:
44
router/__init__.py
Normal file
44
router/__init__.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import importlib
|
||||
import pkgutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter
|
||||
from uvicorn.server import logger
|
||||
|
||||
# 定义一个 APIRouter 实例
|
||||
router = APIRouter()
|
||||
|
||||
# 初始化 __all__ 列表,用于声明模块公开的对象
|
||||
__all__ = []
|
||||
|
||||
# 获取当前文件所在目录
|
||||
current_dir = Path(__file__).parent
|
||||
|
||||
# 定义可能的路由变量名列表
|
||||
ROUTER_VARIABLE_NAMES = ["router", "routes", "api_router"]
|
||||
|
||||
# 遍历当前目录下的所有 .py 文件
|
||||
for module_info in pkgutil.iter_modules([str(current_dir)]):
|
||||
if module_info.name != Path(__file__).stem: # 排除当前文件
|
||||
module = importlib.import_module(f".{module_info.name}", package=__package__)
|
||||
found_router = False
|
||||
# 遍历可能的路由变量名
|
||||
for var_name in ROUTER_VARIABLE_NAMES:
|
||||
if hasattr(module, var_name):
|
||||
module_router: APIRouter = getattr(module, var_name)
|
||||
api_number = len(module_router.routes)
|
||||
logger.info(
|
||||
f"[导入路由] 已导入模块: {module_info.name}.{var_name} 共计{api_number}个接口 ✅"
|
||||
)
|
||||
# 自动创建别名,使用模块名和变量名组合作为别名
|
||||
alias_name = f"{module_info.name}_{var_name}"
|
||||
globals()[alias_name] = module_router
|
||||
# 包含模块的 router 到主 router 中
|
||||
router.include_router(module_router, tags=[f"{alias_name} api"])
|
||||
# 将别名添加到 __all__ 列表中
|
||||
__all__.append(alias_name)
|
||||
found_router = True
|
||||
if not found_router:
|
||||
logger.error(
|
||||
f"[导入路由] 未导入模块:{module_info.name},未找到以下任一变量: {', '.join(ROUTER_VARIABLE_NAMES)} "
|
||||
)
|
||||
48
router/auth.py
Normal file
48
router/auth.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import json
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from uvicorn.server import logger
|
||||
from utils.wxcom import wxcpt
|
||||
from utils.wxcom import (
|
||||
decrypt_message,
|
||||
get_request_params
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/callback")
|
||||
async def verify_url(msg_signature: str, timestamp: str, nonce: str, echostr: str):
|
||||
"""验证URL有效性"""
|
||||
try:
|
||||
logger.info(
|
||||
f"收到验证请求: msg_signature={msg_signature}, timestamp={timestamp}, nonce={nonce}"
|
||||
)
|
||||
ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
|
||||
|
||||
if ret == 0:
|
||||
logger.info("URL验证成功")
|
||||
return PlainTextResponse(content=sEchoStr)
|
||||
else:
|
||||
logger.error(f"URL验证失败,错误码: {ret}")
|
||||
raise HTTPException(status_code=400, detail="验证失败")
|
||||
except Exception as e:
|
||||
logger.error(f"验证过程发生错误: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="服务器内部错误")
|
||||
|
||||
@router.post("/callback")
|
||||
async def receive_message(request: Request):
|
||||
"""接收并处理企业微信消息"""
|
||||
try:
|
||||
|
||||
# 获取请求参数并验证,返回请求体、消息签名、时间戳和随机数
|
||||
body, msg_signature, timestamp, nonce = await get_request_params(request)
|
||||
# 对请求体进行解密,得到解密后的消息字典
|
||||
xml_dict : dict= decrypt_message(body, msg_signature, timestamp, nonce)
|
||||
logger.info(f"解密后的消息字典: \n {json.dumps(xml_dict.get("xml") , ensure_ascii=False , indent=2)}")
|
||||
# 处理消息
|
||||
# subscription(xml_dict)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理消息时发生错误: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="服务器内部错误")
|
||||
Reference in New Issue
Block a user