Browse Source

代码提交

SGTY 1 tháng trước cách đây
mục cha
commit
f720aebb1e
2 tập tin đã thay đổi với 110 bổ sung51 xóa
  1. 38 38
      src/knowledge/middlewares/base.py
  2. 72 13
      src/knowledge/router/knowledge_nodes_api.py

+ 38 - 38
src/knowledge/middlewares/base.py

@@ -185,49 +185,49 @@ class AuthMiddleware(BaseHTTPMiddleware):
         # 初始化操作:将用户信息添加到请求状态中
         request.state.user = user_info
         #cache["license_info"]是否存在license信息,如果不存在则验证证书
-        if not 'license_info' in self._cache or not self._cache["license_info"]:
-            lisence_detail = license_handle()
-            #判断license_info是否是个json,且存在key为expiration_time的字段,如果存在则判断是否过期
-            if lisence_detail and "expiration_time" in lisence_detail:
-                license_info = json.loads(lisence_detail)
-                expiration_time = license_info.get("expiration_time")
-                if expiration_time and expiration_time < time.time():
-                    return self.set_auth_err_resp("License expired")
-                else:
-                    self._cache["license_info"] = license_info
-            else:
-                return self.set_auth_err_resp(lisence_detail)
-
-            if hasattr(self, '_invok_info'):
-                current_count = self._invok_info.get('api_invoke_count', 0)
-                  # 从字典服务获取调用次数的枚举值
-                dict_service = DictSystemService(self.db)
-                try:
-                    call_count_dict = dict_service.get_dicts_by_name('api_invoke_count') 
-                    old_increment_value = int(call_count_dict.dict_value)
-                    
-                    # 更新调用次数
-                    updated_count = current_count + old_increment_value
-                    
-                    # 更新数据库中的调用次数
-                    dict_service.update_dict(call_count_dict['id'], {'dict_value': str(updated_count)})
-                    self._invok_info['api_invoke_count'] = 0
-
-                    api_invoke_max_count = license_info.get("content")[0].get("api_invoke_max_count") 
-                    if updated_count >= api_invoke_max_count:
-                        return self.set_auth_err_resp("调用次数已达上限!")
-                except Exception as e:
-                    logger.error(f"更新调用次数失败: {str(e)}")
+        # if not 'license_info' in self._cache or not self._cache["license_info"]:
+        #     lisence_detail = license_handle()
+        #     #判断license_info是否是个json,且存在key为expiration_time的字段,如果存在则判断是否过期
+        #     if lisence_detail and "expiration_time" in lisence_detail:
+        #         license_info = json.loads(lisence_detail)
+        #         expiration_time = license_info.get("expiration_time")
+        #         if expiration_time and expiration_time < time.time():
+        #             return self.set_auth_err_resp("License expired")
+        #         else:
+        #             self._cache["license_info"] = license_info
+        #     else:
+        #         return self.set_auth_err_resp(lisence_detail)
+        #
+        #     if hasattr(self, '_invok_info'):
+        #         current_count = self._invok_info.get('api_invoke_count', 0)
+        #           # 从字典服务获取调用次数的枚举值
+        #         dict_service = DictSystemService(self.db)
+        #         try:
+        #             call_count_dict = dict_service.get_dicts_by_name('api_invoke_count')
+        #             old_increment_value = int(call_count_dict.dict_value)
+        #
+        #             # 更新调用次数
+        #             updated_count = current_count + old_increment_value
+        #
+        #             # 更新数据库中的调用次数
+        #             dict_service.update_dict(call_count_dict['id'], {'dict_value': str(updated_count)})
+        #             self._invok_info['api_invoke_count'] = 0
+        #
+        #             api_invoke_max_count = license_info.get("content")[0].get("api_invoke_max_count")
+        #             if updated_count >= api_invoke_max_count:
+        #                 return self.set_auth_err_resp("调用次数已达上限!")
+        #         except Exception as e:
+        #             logger.error(f"更新调用次数失败: {str(e)}")
                 
         # 继续处理请求
         response = await call_next(request)
 
         # 统计调用次数
-        if not hasattr(self, '_invok_info'):
-            self._invok_info = TTLCache(maxsize=20)
-        
-        current_count = self._invok_info.get('api_invoke_count', 0)
-        self._invok_info['api_invoke_count'] = current_count + 1
+        # if not hasattr(self, '_invok_info'):
+        #     self._invok_info = TTLCache(maxsize=20)
+        #
+        # current_count = self._invok_info.get('api_invoke_count', 0)
+        # self._invok_info['api_invoke_count'] = current_count + 1
         # 可以在返回前添加统一响应处理(如添加头信息)
         # response.headers["request-id"] = request.state.context["request_id"]
 

+ 72 - 13
src/knowledge/router/knowledge_nodes_api.py

@@ -22,10 +22,6 @@ class PaginatedSearchRequest(BaseModel):
     pageNo: int = 1
     limit: int = 10
 
-class GetNodeRelationshipsRequest(BaseModel):
-    relation_name: Optional[str] = None
-
-
 async def get_request_id(request: Request):
     return request.state.context["request_id"]
 
@@ -72,7 +68,8 @@ async def paginated_search(
                 error_msg=str(e)
             )
         )
-
+class GetNodeRelationshipsRequest(BaseModel):
+    relation_name: Optional[str] = None
 @router.post("/nodes/{src_id}/relationships", response_model=StandardResponse)
 async def get_node_relationships_condition(
     src_id: int,
@@ -96,11 +93,11 @@ async def get_node_relationships_condition(
             dest_props = []
             edge_props = []
             #count += 1
-            #dest_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
-            #              for p in prop_service.get_props_by_ref_id(dest_node['id'])]
+            dest_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
+                          for p in prop_service.get_props_by_ref_id(dest_node['id'])]
             
-            #edge_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
-            #             for p in prop_service.get_props_by_ref_id(edge['id'])]
+            edge_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
+                         for p in prop_service.get_props_by_ref_id(edge['id'])]
 
             relationships.append({
                 "name": edge['name'],
@@ -145,11 +142,62 @@ async def get_node_relationships(
             dest_props = []
             edge_props = []
             # count += 1
-            # dest_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
-            #              for p in prop_service.get_props_by_ref_id(dest_node['id'])]
+            dest_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
+                          for p in prop_service.get_props_by_ref_id(dest_node['id'])]
+
+            edge_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
+                         for p in prop_service.get_props_by_ref_id(edge['id'])]
+
+            relationships.append({
+                "name": edge['name'],
+                "props": edge_props,
+                "destNode": {
+                    "category": dest_node['category'],
+                    "id": str(dest_node['id']),
+                    "name": dest_node['name'],
+                    "props": dest_props
+                }
+            })
+
+        return StandardResponse(
+            success=True,
+            requestId=request_id,
+            data=ObjectToJsonArrayConverter.convert({"relationships": relationships})
+        )
+    except Exception as e:
+        logger.error(f"获取节点关系失败: {str(e)}")
+        raise HTTPException(500, detail=StandardResponse.error(str(e)))
+
+class GetNodeProperties(BaseModel):
+    property_name: Optional[str] = None
+@router.post("/nodes/{node_id}/properties", response_model=StandardResponse)
+async def get_node_properts(
+    node_id: int,
+    payload: GetNodeProperties,
+    db: Session = Depends(get_db),
+    request_id: str = Depends(get_request_id),
+    api_key: str = Security(api_key_header)
+):
+    try:
+
+        prop_service = KGPropService(db)
+
+        edges = edge_service.get_edges_by_nodes(src_id=src_id, dest_id=None)
+        relationships = []
+
+        # count = 0
+        for edge in edges:
+            # if count >= 2:
+            # break
+            dest_node = edge['dest_node']
+            dest_props = []
+            edge_props = []
+            # count += 1
+            dest_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
+                          for p in prop_service.get_props_by_ref_id(dest_node['id'])]
 
-            # edge_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
-            #             for p in prop_service.get_props_by_ref_id(edge['id'])]
+            edge_props = [{'prop_title': p['prop_title'], 'prop_value': p['prop_value']}
+                          for p in prop_service.get_props_by_ref_id(edge['id'])]
 
             relationships.append({
                 "name": edge['name'],
@@ -170,4 +218,15 @@ async def get_node_relationships(
     except Exception as e:
         logger.error(f"获取节点关系失败: {str(e)}")
         raise HTTPException(500, detail=StandardResponse.error(str(e)))
+
+class GetEdgeProperties(BaseModel):
+    property_name: Optional[str] = None
+@router.post("/edges/{edge_id}/properties", response_model=StandardResponse)
+async def get_node_relationships_condition(
+        edge_id: int,
+        payload: GetEdgeProperties,
+        db: Session = Depends(get_db),
+        request_id: str = Depends(get_request_id),
+        api_key: str = Security(api_key_header)
+):
 knowledge_nodes_api_router = router