When encapsulating your own database tool class , First use pymysql.connect, Pass in different configurations , But in use The configuration information is written into the program , The coupling is too high , Such as :
Then the idea is to use io Read and write files , Setting configuration information ; however :io There may be permission problems when reading , As far as possible with import Import . The compiler will help you process the data into memory , Finally, I found this way of writing :
Definition setting.py, With json In the form of data storage
db_config={
'host': '192.168.xxx.xxx',
'user': 'root',
'password': 'xxx',
'db': 'xxx',
}
Used when calling import The import module
from setting import db_config
import pymysql
conn = pymysql.connect(**db_config)
with conn:
print(conn.open) # True
Finally, the configuration information and code are successfully decoupled , Modifying the configuration information does not need to change the source code