写一个类,读取以下配置{ "dbconfig": { "mongo": { "host": "127.0.0.1", "port": 27017, "username": "user", "password": "userpwd", "db": "index" }, "mysql": { "host": "127.0.0.1", "port": 3306, "username": "user", "password": "userpwd", "db": "dbname" }, "query": { "pagesize": 25, "format": "json" } }, "mqserver": { "mqtt": { "host": "127.0.0.1", "port": 1883, "username": "mqtt-test", "password": "mqtt-test", "exchange": "/mqtt.topic", "message": { "device_num": 10, "send_sleep": 2, "gps_config": { "center_lat": "", "center_lng": " ", "gps_mode": "wgs84" } } } } }
时间: 2023-02-05 13:44:11 浏览: 193
一个用于读写配置文件的类
以下是一个 Python 类的例子,可以读取上述配置:
```
import json
class Config:
def __init__(self, config_file):
with open(config_file, 'r') as f:
self.config = json.load(f)
def get_dbconfig(self):
return self.config['dbconfig']
def get_mongo_config(self):
return self.config['dbconfig']['mongo']
def get_mysql_config(self):
return self.config['dbconfig']['mysql']
def get_query_config(self):
return self.config['dbconfig']['query']
def get_mqserver_config(self):
return self.config['mqserver']
def get_mqtt_config(self):
return self.config['mqserver']['mqtt']
def get_mqtt_message(self):
return self.config['mqserver']['mqtt']['message']
def get_gps_config(self):
return self.config['mqserver']['mqtt']['message']['gps_config']
```
使用方法:
```
config = Config('config.json')
dbconfig = config.get_dbconfig()
mongo_config = config.get_mongo_config()
mysql_config = config.get_mysql_config()
query_config = config.get_query_config()
mqserver_config = config.get_mqserver_config()
mqtt_config = config.get_mqtt_config()
mqtt_message = config.get_mqtt_message()
gps_config = config.get_gps_config()
```
在这个类中,我们定义了一些方法来获取不同的配置信息。例如,可以使用 `get_dbconfig` 方法来获取数据库配置,使用 `get_mongo_config` 方法来获取 MongoDB 的配置,使用 `get_mqtt_config` 方法来获取 MQTT 服务器的配置等。
注意:在这个例子中,我们假设配置信息存储在名为 `config.json` 的文件中。
阅读全文