一、在配置文件中配置相关连接参数
在conf.ini中:
#mysql参数
[Mysql]
host = 192.168.1.2
port = 3306
user = root
passwd = pswdmysql
db = student
#InfluxDB参数
[InfluxDB]
host = 192.168.1.3
port = 8086
user = root
passwd = pswdinflux
db = student
#Redis参数
[InfluxDB]
host = 192.168.1.4
port = 6379
user = root
passwd = pswdredis
二、读取配置文件参数,返回连接对象``
/usr/bin/env python
coding:utf-8
auther:yuanmuc
connect to mysql,influxdb,redis
from influxdb import InfluxDBClient
import MySQLdb
import redis
import sys
reload(sys)
sys.setdefaultencoding(‘uft-*8‘)
def DBcon():
cf = ConfigParser.SafeConfigParser()
cf.read("conf.ini")
mysql的参数
MysqlHost = cf.get(‘Mysql‘,‘host‘)
MysqlPort = cf.get(‘Mysql‘,‘port‘)
MysqlUser = cf.get(‘Mysql‘, ‘user‘)
MysqlPwd = cf.get(‘Mysql‘, ‘passwd‘)
MysqlDb = cf.get(‘Mysql‘, ‘db‘)
influxdb的参数
InfHost = cf.get(‘InfluxDB‘,‘host‘)
InfPort = cf.get(‘InfluxDB‘, ‘port‘)
InfUser = cf.get(‘InfluxDB‘, ‘user‘)
InfPwd = cf.get(‘InfluxDB‘, ‘passwd‘)
InfDB = cf.get(‘InfluxDB‘, ‘db‘)
redis的参数
RedisHost = cf.get(‘Redis‘,‘host‘)
RedisPort = cf.get(‘Redis‘, ‘port‘)
RedisUser = cf.get(‘Redis‘, ‘user‘)
RedisPwd = cf.get(‘Redis‘, ‘passwd‘)
#连接mysql
MysqlCon = MySQLdb.connect(host=MysqlHost,port=int(MysqlPort),user=MysqlUser,passwd=MysqlPwd,db=MysqlDb,charset=‘utf-8‘)
MysqlCur = MysqlCon.cursor()
#连接influxdb
Influxdb_Client = InfluxDBClient(InfHost,InfPort,InfUser,InfPwd,InfDB)
#连接redis
pool = redis.ConnectionPool(host=RedisHost,port=RedisPort,password=RedisPwd,decode_responses=True)
Redis_Client = redis.Redis(connection_pool=pool)
返回连接
return MysqlCon,MysqlCur,Influxdb_Client,Redis_Client
def MysqlClose():
MysqlCon.close()
MysqlCur.close()
if __name__ == ‘__main__‘:
MysqlCon, MysqlCur, Influxdb_Client, Redis_Client = DBcon()
原文地址:http://blog.51cto.com/12824426/2174471
时间: 2024-10-29 10:28:07