Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Read the ini configuration file through python

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

What is ini?

You can understand it as a general term for a configuration file. For example, test.conf, you can understand that it is an ini file, which generally stores some configuration information. For example, the basic information of the database, we will explain it later!

So what are the benefits of ta? Is to put some configuration information out for separate management, if there are changes in the future, you only need to change the configuration file, there is no need to modify the code.

Basic format in ini

[name, just write it according to the actual situation, nothing particular]

Key1=value1

Key2=value2

Read operation is carried out through ConfigParser module in python

Actual combat

Demo scenario:

1. Create a database configuration file named db.conf, which contains the following contents:

[DATABASE]

Host = 127.0.0.1

Port = 3306

User = root

Passwd = vertrigo

Db = testdb

Charset = utf8

2. Read the information in python and connect to the database. The code is as follows:

Import configparser

Import mysql.connector

Class GetDB:

Def _ _ init__ (self, db_config):

Config = configparser.ConfigParser ()

Config.read (db_config)

# read and save the data in the configuration file

Self.host = config ['DATABASE'] [' host']

Self.port = config ['DATABASE'] [' port']

Self.user = config ['DATABASE'] [' user']

Self.passwd = config ['DATABASE'] [' passwd']

Self.db = config ['DATABASE'] [' db']

Self.charset = config ['DATABASE'] [' charset']

# here is the linked database

Def get_conn (self):

Try:

Conn = mysql.connector.connect (host=self.host, port=self.port, user=self.user, password=self.passwd, database=self.db, charset=self.charset)

Return conn

Except Exception as e:

Print ('% slots, e)

Sys.exit ()

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report