采用http报送resource

This commit is contained in:
Xuwznln
2025-07-19 10:38:58 +08:00
parent c2dfe689aa
commit fd18b21147
5 changed files with 123 additions and 38 deletions

View File

@@ -18,10 +18,22 @@ def register_devices_and_resources(mqtt_client, lab_registry):
mqtt_client.publish_registry(device_info["id"], device_info, False)
logger.debug(f"[UniLab Register] 注册设备: {device_info['id']}")
# 注册资源信息
# 注册资源信息 - 使用HTTP方式
from unilabos.app.web.client import http_client
resources_to_register = {}
for resource_info in lab_registry.obtain_registry_resource_info():
mqtt_client.publish_registry(resource_info["id"], resource_info, False)
logger.debug(f"[UniLab Register] 注册资源: {resource_info['id']}")
resources_to_register[resource_info["id"]] = resource_info
logger.debug(f"[UniLab Register] 准备注册资源: {resource_info['id']}")
if resources_to_register:
start_time = time.time()
response = http_client.resource_registry(resources_to_register)
cost_time = time.time() - start_time
if response.status_code in [200, 201]:
logger.info(f"[UniLab Register] 成功通过HTTP注册 {len(resources_to_register)} 个资源 {cost_time}ms")
else:
logger.error(f"[UniLab Register] HTTP注册资源失败: {response.status_code}, {response.text} {cost_time}ms")
time.sleep(10)
@@ -53,11 +65,9 @@ def main():
help="是否补全注册表",
)
args = parser.parse_args()
load_config_from_file(args.config)
# 构建注册表
build_registry(args.registry, args.complete_registry)
load_config_from_file(args.config)
from unilabos.app.mq import mqtt_client
# 连接mqtt
@@ -70,4 +80,4 @@ def main():
if __name__ == "__main__":
main()
main()

View File

@@ -40,8 +40,9 @@ class HTTPClient:
Returns:
Response: API响应对象
"""
database_param = 1 if database_process_later else 0
response = requests.post(
f"{self.remote_addr}/lab/resource/edge/batch_create/?database_process_later={1 if database_process_later else 0}",
f"{self.remote_addr}/lab/resource/edge/batch_create/?database_process_later={database_param}",
json=resources,
headers={"Authorization": f"lab {self.auth}"},
timeout=100,
@@ -149,6 +150,26 @@ class HTTPClient:
)
return response
def resource_registry(self, registry_data: Dict[str, Any]) -> requests.Response:
"""
注册资源到服务器
Args:
registry_data: 注册表数据,格式为 {resource_id: resource_info}
Returns:
Response: API响应对象
"""
response = requests.post(
f"{self.remote_addr}/lab/registry/",
json=registry_data,
headers={"Authorization": f"lab {self.auth}"},
timeout=30,
)
if response.status_code not in [200, 201]:
logger.error(f"注册资源失败: {response.status_code}, {response.text}")
return response
# 创建默认客户端实例
http_client = HTTPClient()