Python 生成和读取数据库INI配置

本文深入解析DBConfig模块的实现细节,包括数据源定义、INI文件的生成与读取,以及数据库配置管理。通过实例展示了如何设置和读取数据库配置。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#    @version : 0.0.1
#    @File    : DBConfig.py
#    @Time    : 2018/8/30 0030 下午 2:46
#    @Site    : 
#    @Software: PyCharm
#    @Author  : singebogo
#    @Author_email: singbogo@163.com
#    @description: 


# 主要功能:
#       1、生成ini文件
#             1、定义数据源
#             2、解析数据
#             3、生成ini文件
#       2、读取ini文件
#             1、读取文件
#             2、获取数据,key-value

#
#             DBconfig
#          /\              /\
#          |               |
#          |               |
#      DBConfigRead    DBConfigSet
#
# 基本数据定义:
#             enum dbtypes {}
#
# DBconfig:  抽象类
#
#         1、属性: dbtype、host、user、password、database、charset
#         2、ABs set get map(key-value)
#         3、Mkdir DbConfig

import os

from new_frame.api.filegener.path.proj import ProjPath
from new_frame.util.STL.dictmaintain import MapCommon,DEFAULTTARGETTYPE
from new_frame.util.logutil.log import logger
from new_frame.util.config.ini import IniConfig


dbConfigName =  'DBConfig.ini'

#---------------------------------------------------------------------------
#   Level related stuff
#---------------------------------------------------------------------------
#
# Default levels and level names, these can be replaced with any positive set
# of values having corresponding names. There is a pseudo-level, NOTSET, which
# is only really there as a lower limit for user-defined levels. Handlers and
# loggers are initialized with NOTSET so that they will log all messages, even
# at user-defined levels.
#
mysql = 0
oracle = 1
sqlserver = 2
access = 3
db2 = 4
sybase = 5
foxbase = 6
# 非关系型数据库
redis = 7
mongodb = 8

DBTYPES = {
    mysql : 'mysql',
    oracle : 'oracle',
    sqlserver : 'sqlserver',
    access : 'access',
    db2 : 'db2',
    sybase : 'sybase',
    foxbase: 'foxbase',
    redis: 'redis',
    mongodb: 'mongodb',
    'mysql': mysql,
    'oracle': oracle,
    'sqlserver': sqlserver,
    'access': access,
    'db2': db2,
    'sybase': sybase,
    'foxbase': foxbase,
    'redis': redis,
    'mongodb': mongodb,
}

targettype =  'dict'

class DBConfig(object):

    configdict = {'dbtype':'','host':'','user' :'','port': '','password':'','database':'','charset':''}

    def __init__(self):
        self.__mkConfigDir()

    def __mkConfigDir(self):
        '''
        创建db配置文件
        @param filename:  文件路径
        @return: True:创建成功 False:创建失败
        '''
        filename = DBConfig.getDbConfigDir()
        print(filename)
        if filename is not None:
            filebase = FileBase(filename)
            if not filebase.isExist():
                return filebase.fileCreate()
        return False

    @staticmethod
    def getDbConfigDir():
        '''
        静态方法,获取配置文件路径
        @return: 返回文件路径
        '''
        configdir = ProjPath.getConfigFile()
        if dbConfigName is not None:
          return os.path.join(configdir, dbConfigName)


from new_frame.api.filegener.fileoperator.filebase import FileBase

class DBConfigRead(DBConfig):

    configfilepath = ''

    def __new__(cls, *args, **kwargs):
        if len(args) == 0:
            filepath = DBConfigRead.getDbConfigDir()
            if not FileBase(filepath).isExist():
                DBConfigRead.configfilepath = filepath
                return object.__new__(cls)
            else:
                logger.error('Config File not exits ' + filepath)
                return
        elif len(args) == 1:
            print FileBase(args[0]).isExist()
            if FileBase(args[0]).isExist():
                DBConfigRead.configfilepath = args[0]
                return object.__new__(cls)
            else:
                logger.error('Config File not exits ' + args[0])
                return
        else:
            return

    def __init__(self, path):
        super(DBConfigRead, self).__init__()

    def readInI(self):
        inicfg = IniConfig(DBConfigRead.configfilepath)
        return inicfg.getAll()

'''
        [mysql]
        dbtype = MySql
        host = 127.0.0.1
        port = 3306
        user = root
        password = 123456
        database = test
        charset = utf8
'''

# {'mysql': {'database': 'selling_expenses_dev', 'dbtype': 'mysql', 'charset': 'utf8', 'host': '127.0.0.1', 'user': 'root', 'password': '123456', 'port': '3306'}}

# *args  **kwargs
class DBConfigSet(DBConfig):

    def __init__(self):
        DBConfig.configdict['dbtype'] = 'mysql'
        DBConfig.configdict['host'] = "127.0.0.1"
        DBConfig.configdict['port'] = 3306
        DBConfig.configdict['user'] = "root"
        DBConfig.configdict['password'] = "123456"
        DBConfig.configdict['database'] = "test"
        DBConfig.configdict['charset'] = "utf8"
        super(DBConfigSet, self).__init__()

    def setInI(self):
        mapcommon = MapCommon(type(DBTYPES).__name__, DEFAULTTARGETTYPE, DBTYPES)
        if mapcommon is None:
            return
        if DBConfig.configdict['dbtype'] == mapcommon.getKeyName(mapcommon.getKeyName(DBConfig.configdict['dbtype'])):
            inicfg = IniConfig(DBConfig.getDbConfigDir())
            root = mapcommon.getKeyName(mapcommon.getKeyName(DBConfig.configdict['dbtype']))
            inicfg.add(root)
            for key, value in DBConfig.configdict.items():
                inicfg.add(root, key, value)

if __name__ == '__main__':
    # print (type(DBTYPES).__name__ == 'dict')
    # print (isinstance(DBTYPES, dict))
    # #  传入的是类型
    # AA = MapCommon(type(DBTYPES).__name__,  targettype, DBTYPES )
    # print(AA)
    # print(AA.getKeyName("mongodb"))
    # BB = 10
    # AA.addKeylName(BB, "CC")
    # AA.addKeylName("CC", BB)
    # DBTYPES = AA.getDict()
    # print(DBTYPES)
    # # print (AA.checkKey(key='VV'))
    # dbconfig = DBConfig()
    # print (dbconfig)
    # dbset = DBConfigSet()
    # print(dbset.setInI())

    path = "D:\\pyt\\new_frame\\config\\DBConfig.ini"
    dbread = DBConfigRead(path)
    print (dbread.readInI())

 

<think>嗯,用户想用Python读取INI配置文件,需要简单的方法示例代码。首先,我得回忆一下Python中处理INI文件的标准库是什么。对了,应该是configparser模块,在Python3中叫做configparser,而Python2可能是ConfigParser。用户可能用的是Python3,所以需要提醒他们注意模块名称的变化。接下来,我需要给出一个简单的步骤。首先是导入模块,然后创建ConfigParser对象,接着读取文件,再获取配置值。可能还需要提到如何处理不同的数据类型,比如getint、getboolean等方法。用户可能希望看到完整的代码示例,包括读取字符串、整数布尔值的例子。还要注意文件路径的问题,用户可能需要指定正确的路径,所以示例代码应该包含如何定义路径。另外,异常处理也是需要考虑的,比如文件不存在或者配置项不存在的情况,但用户可能只需要基础用法,暂时可以不提高级部分。然后,根据用户提供的引用内容,引用1到5都提到了configparser的使用,所以需要确保代码符合这些引用中的方法。比如引用4中的代码示例使用了ConfigParser.ConfigParser(),这在Python2中是正确的,但Python3中应改为configparser.ConfigParser()。需要提醒用户注意Python版本的差异。可能还需要提到如何写入INI文件,但用户的问题主要是读取,所以写入可以作为额外补充。此外,注释部分如果有中文,可能需要指定编码,如引用3提到的,在Python3中读取时要加encoding='utf-8'参数,避免乱码问题。 最后,生成的相关问题应该围绕INI文件的读取,比如不同数据类型的处理、异常处理、写入配置等,这样用户如果有进一步的问题可以参考。</think>### 如何用Python读取INI配置文件 #### 步骤说明 1. **导入模块**:使用`configparser`模块(Python3名称,Python2为`ConfigParser`) 2. **创建实例**:实例化`ConfigParser`类 3. **读取文件**:调用`read()`方法加载INI文件 4. **获取配置值**:通过`get()`, `getint()`, `getboolean()`等方法读取具体值 #### 示例代码 ```python import configparser # 1. 创建ConfigParser对象 config = configparser.ConfigParser() # 2. 读取INI文件(注意路径编码) config.read('config.ini', encoding='utf-8') # 3. 获取配置值(示例section为[database]) host = config.get('database', 'host') port = config.getint('database', 'port') debug_mode = config.getboolean('settings', 'debug') print(f"数据库地址:{host}, 端口:{port}") print(f"调试模式:{debug_mode}") ``` #### 关键点说明 - **数据类型处理**:`getint()`用于读取整数,`getboolean()`可识别`true/false`或`1/0`[^5] - **文件编码**:若INI文件含中文,需指定`encoding='utf-8'`[^3] - **路径处理**:建议使用绝对路径或动态获取当前脚本路径 - **异常处理**:可包裹`try-except`块捕获`NoSectionError`或`NoOptionError` #### 扩展应用 ```python # 写入配置示例(需注意文件权限) config.set('settings', 'timeout', '30') with open('config.ini', 'w') as f: config.write(f) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值