From 10e708df86bf0575c2233b34de8ce914d08638a5 Mon Sep 17 00:00:00 2001 From: chenpanliang <3245129380@qq.com> Date: Mon, 22 Dec 2025 18:35:22 +0800 Subject: [PATCH] =?UTF-8?q?feat(a1-card):=20=E6=96=B0=E5=A2=9EA1=E5=90=8D?= =?UTF-8?q?=E7=89=87=E8=B7=AF=E7=94=B1=E5=92=8C=E6=9C=8D=E5=8A=A1=E6=A8=A1?= =?UTF-8?q?=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加a1_card_router路由模块,实现根据企业微信ID获取用户画像数据的功能 包含路由注册、服务层实现及MongoDB查询逻辑 --- src/main.py | 3 +- src/routers/__init__.py | 4 +-- src/routers/a1_card.py | 56 +++++++++++++++++++++++++++++++++ src/services/a1_card.py | 69 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 src/routers/a1_card.py create mode 100644 src/services/a1_card.py diff --git a/src/main.py b/src/main.py index 3d69124..15bbf33 100644 --- a/src/main.py +++ b/src/main.py @@ -32,9 +32,10 @@ app.add_middleware( ) # 注册路由模块 -from src.routers import wechat_router, light_router +from src.routers import wechat_router, light_router, a1_card_router app.include_router(wechat_router, prefix=API_PREFIX+"/wechat", tags=["企业微信"]) app.include_router(light_router, prefix=API_PREFIX+"/light", tags=["信息灯牌"]) +app.include_router(a1_card_router, prefix=API_PREFIX+"/a1-card", tags=["A1名片"]) # 根路径端点,返回欢迎信息 @app.get(API_PREFIX+"/") diff --git a/src/routers/__init__.py b/src/routers/__init__.py index 4495dbc..a359e78 100644 --- a/src/routers/__init__.py +++ b/src/routers/__init__.py @@ -2,5 +2,5 @@ from src.routers.wechat import wechat_router from src.routers.light import light_router - -__all__ = ["wechat_router", "light_router"] +from src.routers.a1_card import a1_card_router +__all__ = ["wechat_router", "light_router", "a1_card_router"] diff --git a/src/routers/a1_card.py b/src/routers/a1_card.py new file mode 100644 index 0000000..3cf747c --- /dev/null +++ b/src/routers/a1_card.py @@ -0,0 +1,56 @@ +from fastapi import APIRouter, HTTPException +from typing import Optional, Dict, Any +from src.services.a1_card import get_user_portrayal_small_by_wecom_id +from src.models.response import success_response, error_response + +# 创建路由实例 +a1_card_router = APIRouter() + + +@a1_card_router.get("/user-portrayal/{customer_wechat_id}", summary="根据customer_wechat_id获取用户画像数据") +async def get_user_portrayal_small(customer_wechat_id: str): + """ + 根据customer_wechat_id查询customers集合中的user_portrayal_small数据 + + - **customer_wechat_id**: 用户的企业微信ID + + Returns: + ResponseModel: 包含用户画像数据的统一响应格式 + """ + if not customer_wechat_id: + return error_response( + message="customer_wechat_id不能为空", + code=400 + ) + + try: + # 调用服务层获取用户画像数据 + portrayal_data = get_user_portrayal_small_by_wecom_id(customer_wechat_id) + + if portrayal_data is not None: + return success_response( + data=portrayal_data, + message="成功获取用户画像数据", + code=200 + ) + else: + return success_response( + data={}, + message="未找到该用户的画像数据", + code=200 + ) + except ValueError as e: + return error_response( + message=str(e), + code=400 + ) + except RuntimeError as e: + return error_response( + message=str(e), + code=500 + ) + except Exception as e: + return error_response( + message=f"获取用户画像数据失败: {str(e)}", + code=500 + ) \ No newline at end of file diff --git a/src/services/a1_card.py b/src/services/a1_card.py new file mode 100644 index 0000000..9559f72 --- /dev/null +++ b/src/services/a1_card.py @@ -0,0 +1,69 @@ +import logging +from typing import Optional, Dict, Any +from src.utils.mongodb import get_mongodb_sync_db + +# 配置日志 +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +if not logger.handlers: + handler = logging.StreamHandler() + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + handler.setFormatter(formatter) + logger.addHandler(handler) + logger.propagate = False # 防止重复记录 + + +def get_customers_collection(): + """ + 获取customers集合 + + Returns: + Collection: MongoDB集合对象 + """ + from src.utils.mongodb import MongoDB + # 确保MongoDB已初始化 + if not MongoDB._sync_initialized: + MongoDB.initialize_sync() + + db = MongoDB.get_sync_db() + collection = db["customers"] + return collection + + +def get_user_portrayal_small_by_wecom_id(wecom_id: str) -> Optional[Dict[str, Any]]: + """ + 根据wecom_id(对应customer_wechat_id)查询customers集合中的user_portrayal_small数据 + + Args: + wecom_id (str): 用户的企业微信ID,对应数据库中的customer_wechat_id字段 + + Returns: + Optional[Dict[str, Any]]: 用户画像数据,如果未找到则返回None + + Raises: + RuntimeError: 当数据库查询出现错误时抛出异常 + """ + try: + # 获取customers集合 + collection = get_customers_collection() + + # 查询条件:wecom_id对应customer_wechat_id字段 + query = {"wecom_id": wecom_id} + + # 只返回user_portrayal_small字段 + projection = {"user_portrayal_small": 1, "_id": 0} + + # 执行查询 + doc = collection.find_one(query, projection) + + # 如果找到了文档,返回user_portrayal_small字段的值 + if doc and "user_portrayal_small" in doc: + return doc["user_portrayal_small"] + + # 如果没有找到匹配的文档或user_portrayal_small字段不存在,返回None + return None + + except Exception as e: + logger.error(f"根据wecom_id({wecom_id})查询用户画像数据时出错: {str(e)}") + raise RuntimeError(f"查询用户画像数据失败: {str(e)}") \ No newline at end of file