场景提要
最近有一个通过 Web 页面调用压测机器人的开发需求。
调用链路为:Web -> Python ->压测机器人
这里有一个需求,就是通过 Web 页面填写机器人配置,由 Python 到服务器增量替换原有的机器人配置,并使用该替换后的新配置启动机器人程序。
开发思路
1、由前端生成配置表单,通过 Web 请求接口方式传递给 Python 程序,Python 以字典格式接收。
conf_dict={
"server.ip" : "192.168.0.1",
"server.robot.task" : "3|4,5,6|7|47",
"server.gateWay.url" : "http://127.0.0.1:8000",
"server.onlyLogin":True,
"server.scenes":"30001,40001" # 这个为增量配置
}
2、由 Python 根据已知的机器人旧配置文件路径进行读取,并以接收到的新配置项与之替换。
# 已知的机器人旧配置文件路径
old_conf_file_path="F:/python/test/test.properties"
旧配置文件里面的配置项(test.properties)
# 测试配置文件
server.ip=192.168.0.1
server.port=20002
# serviceId
server.serviceId=100001
# GateWay
server.gateWay.url=http://127.0.0.1:8000
# 任务配置
server.robot.task=3|4,5,6|7|47
# 只执行登录任务
server.onlyLogin=True
如何增量替换原有配置
当然是使用 Python 强大的 os 标准库了
代码实现
直接简单粗暴一点,上代码。(备注:以下代码是在 Python2.7 环境下实现的!)
# -*- coding: utf-8 -*-
# @Author : lei_0668@sina.com
# @Time : 2022-11-03
# @File : replace_conf.py
import os
class Test:
def replace_config(self, new_conf_dict, old_conf_file_path):
# 读取旧配置
old_conf_arr = self.read_old_config(old_conf_file_path)
# 这里为核心逻辑,以新配置字典去增量替换旧配置的值
new_conf_arr = self.deal_conf(old_conf_arr=old_conf_arr, conf_dict=conf_dict)
# 写入替换好的新配置
with open(name=old_conf_file_path, mode="w") as fd:
fd.writelines(new_conf_arr)
return {"code":0, "msg":u"文件替换完成"}
# 读取旧文件
def read_old_config(self, old_conf_file_path):
if os.path.isfile(path=old_conf_file_path) is False:
return {"code":127, "msg":u"旧文件路径不存在"}
with open(name=old_conf_file_path, mode="r") as fd:
conf_data = fd.readlines()
return conf_data
# 用新的配置替换旧配置
def deal_conf(self, old_conf_arr, conf_dict):
for key in conf_dict.iterkeys():
old_conf_arr = self.replace_conf_line(old_conf_arr=old_conf_arr, key=key, value=conf_dict.get(key))
return old_conf_arr
# replace
def replace_conf_line(self, old_conf_arr, key, value):
is_write = False
new_conf_arr = list()
for line in old_conf_arr:
# 注释不去除空格
if (line.find("#") == -1):
line = line.replace(" ", "")
# 根据新的key查找旧配置是否存在,如果存在则替换
note_index = line.find(str(key) + "=")
if note_index != -1:
new_conf_arr.append(key + "=" + str(value) + "\n")
is_write = True
else:
new_conf_arr.append(line)
if is_write is False:
new_conf_arr.append("\n" + key + "=" + str(value))
return new_conf_arr
# 测试
test = Test()
# 接收的新配置字典
conf_dict={
"server.ip" : "192.168.0.1",
"server.robot.task" : "3|4,5,6|7|47",
"server.gateWay.url" : "http://127.0.0.1:8000",
"server.onlyLogin":True,
"server.scenes":"30001,40001" # 这个为增量配置
}
print test.replace_config(new_conf_dict=conf_dict, old_conf_file_path="F:/python/test/test.properties")