程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Package read configuration class Python & Java implementation

編輯:Python

scene :

The configuration information of a server program is stored in a file , Client through a AppConfig Class to read configuration file information . If during the program run , There are a lot of places where you need to use the content of a profile , in other words , Many places need to create AppConfig Instance of object , This results in multiple AppConfig Instance object of , And this is a serious waste of memory resources , Especially when the configuration file has a lot of content . in fact , similar AppConfig Such a class , We want to have only one instance object during program execution .

One 、python Realization :

1.1 Read a single configuration file

Database configuration file configuration.yml

DB:
host: 1
username: 12
password: 12
database: 14
databasetype: 15
port: 33
note: C

Custom class MyDbinfo, Storage database configuration


import yaml
from singleton import singleton
@singleton
class MyDbinfo(object):
def __init__(self):
_filePath = "/Users/zhaohui/PycharmProjects/TestSingleton/configuration.yml"
f = open(_filePath, 'r', encoding='utf-8')
cont = f.read()
x = yaml.load(cont, Loader=yaml.FullLoader)
self.host =x['DB']['host']
self.username=x['DB']['username']
self.password=x['DB']['password']
self.database=x['DB']['database']
self.port=x['DB']['port']
self.note = x['DB']['note']

Here we use the annotated singleton pattern singleton

def singleton(cls,*args,**kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args,**kw)
return instances[cls]
return _singleton

Let's call it

from MyDbinfo import MyDbinfo
myDbinfo1 = MyDbinfo()
myDbinfo2 = MyDbinfo()
if __name__ == '__main__':
print(myDbinfo1)
print(myDbinfo2)

Print the results :

<MyDbinfo.MyDbinfo object at 0x7fb610194110>
<MyDbinfo.MyDbinfo object at 0x7fb610194110>

The physical addresses of the two instances are the same , Description is single example .

1.2 Read multiple database files

Create a new class ,DbInfo Store database information


class DbInfo():
# Assign values directly in the constructor , It seems that you should not write attributes . The province get and set The method ?
def __init__(self,host=None,username=None,password=None,database=None,databasetype=None,port=None,note=None,charset="utf8"):
self.host: str = host
self.username: str= username
self.password: str = password
self.database: str = database
self.databasetype: str = databasetype
self.port: str = port
self.note:str = note
self.charset:str = charset

Write a read method , Enter the address of the file , Output DbInfo

YmlUtil.py


import yaml
from DbInfo import DbInfo
class YmlUtil():
# path = os.path.abspath()
@staticmethod
def readDbYml(filePath:str) -> DbInfo:
f = open(filePath, 'r', encoding='utf-8')
cont = f.read()
x = yaml.load(cont,Loader=yaml.FullLoader)
print(x['DB'])
print(x['DB']['host'])
dbInfo=DbInfo(host=x['DB']['host'],
username=x['DB']['username'],
password=x['DB']['password'],
database=x['DB']['database'],
port=x['DB']['port']
)
# Set class properties ——setattr(object,key,value)
# Similar to the builder model
setattr(dbInfo,"note",x['DB']['note'])
return dbInfo

Annotated singleton mode :

singleton.py

def singleton(cls,*args,**kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args,**kw)
return instances[cls]
return _singleton

Get the method of the entity class

@singleton
def getMyDbinfo():
return YmlUtil.readDbYml("/Users/zhaohui/PycharmProjects/TestSingleton/configuration.yml")

Test to get the entity class

 a = getMyDbinfo()
b = getMyDbinfo()
print(a)
print(b)

Print the results :

<DbInfo.DbInfo object at 0x7f9a783b0ed0>
<DbInfo.DbInfo object at 0x7f9a783b0ed0>

The entity class thus obtained , It's also a single case .

Two 、Java Realization


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved