直接上代码
from exec import *
from fastapi import APIRouter, BackgroundTasks
from pydantic import BaseModel, Field
import asyncio
import time
class ConfigModel(BaseModel):
control_vm_conf: dict = Field(title="master配置信息", default={})
slaver_vm_conf: dict = Field(title="执行机配置信息", default={})
# 更新config配置的接口
@Router.post("/UpdateConfig", tags=["UpdateConfig"])
async def update_config(config_data: ConfigModel, backgroundTasks: BackgroundTasks):
if config_data.control_vm_conf:
print("更新config配置,标记为master")
backgroundTasks.add_task(update_vm_config, "master", config_data.control_vm_conf)
elif config_data.slaver_vm_conf:
print("更新config配置,标记为slaver")
backgroundTasks.add_task(update_vm_config, "slaver", config_data.slaver_vm_conf)
else:
print("缺少参数")
return {"message": "config任务已提交"}
async def update_vm_config(vm_type: str, new_config: dict):
"""更新config配置"""
key_list = ["control_mgmt_ip", "control_mgmt_netmask", "control_mgmt_gateway"]
new_config_copy = new_config.copy()
print(new_config)
if vm_type == "master":
# 检查传到参数 是否有数组中的字段
for k in new_config_copy.keys():
if not key_list.__contains__(k):
if k == "control_mgmt_netmask":
new_config["control_mgmt_netmask"] = "255.254.0.0"
elif k == "control_mgmt_gateway":
new_config["control_mgmt_gateway"] = "10.172.55.53"
else:
print("config缺少{}字段".format(k))
else:
for k in new_config_copy.keys():
if key_list.__contains__(k):
new_config.pop(k)
print("非master的config配置不允许有{}字段,已删除!".format(k))
# 全量替换
with open(r"C:\test\bin\config.json", "w") as f:
f.write(json.dumps(new_config))
# 停监听
Config.take_effect_config(vm_type)
# 配ip
if vm_type != "master":
asyncio.create_task(Config.delete_mgmt_ip())
结果为: 1、接口先返回字典 {“message”: “config任务已提交”} 消息,状态为200 2、后台继续执行update_vm_config函数,直到完成
|