json文件
{ ?"mysql":{ ???"hosts":"localhost", ???"user":"root", ???"password":"admin", ???"port":3306, ???"dbname":"jfg", ???"chart":"utf-8"}, ?"redis":{ ???"host":"localhost", ???"user":"test1", ???"password":"test123test", ???"port":"6379" ?}}
python中json的用法
import jsonload 将文件中json的文件读取出来loads 将json的字符串转换成字典jump 将文件中的字符串写入到json的文件中jumps 将字典转换成字符串cur_path = os.path.dirname(os.path.realpath(__file__)) #当前文件夹下的路径,更加的方便。不需要将路径写死print cur_path#json中load的使用#第一种方法with open(‘c:\peizhi.json’,‘r‘) as f: ?????????db = json.load(f)#第二种方法(不写死路径)with open(cur_path + "\\" + "peizhi",‘r‘) as f: ?????????db = json.load(f)jumps的用法a ?= { ???"a" : "123", ???"b" : "456" }b = json.jumps(a)print b #打印出来的是json的值print type(b) #查看一下json的类型jumpwith open(‘‘c:\test.json","w") as d: ?????check = json.dump(a)#写入json中
将配置文件中读取的内容。使用静态的方式显示
import os,json,loggerclass DB_Confg(): ???‘‘‘读取mysql的json配置文件‘‘‘ ???cur_path = os.path.dirname(os.path.realpath(__file__)) ???try: ???????if not os.path.exists(cur_path + "\\" + "peizhi"): ???????????log.info("缺少配置文件") ???????with open(cur_path + "\\" + "peizhi",‘r‘) as f: ???????????db = json.load(f) ???except Exception as e: ???????print "Error %s" %e ???@staticmethod #静态方法 ???def User_sql(): ???????return DB_Confg.db["mysql"]["user"] ???@staticmethod ???def Password_Sql(): ???????return DB_Confg.db["mysql"]["password"] ???@staticmethod ???def Host_Sql(): ???????return DB_Confg.db["mysql"]["hosts"] ???@staticmethod ???def Port_Sql(): ???????return DB_Confg.db["mysql"]["port"] ???@staticmethod ???def Dbname_Sql(): ???????return DB_Confg.db["mysql"]["dbname"] ???@staticmethod ???def Charset_Sql(): ???????return DB_Confg.db["mysql"]["chart"]
import MySQLdbfrom comm.mod_config import *class MysqldbHelper: ???#获取数据库连接
???#获取数据库的连接中,有很多的参数需要写入。每次手动写。很麻烦把。直接就从配置文件中更改就很方便。虽然很不方便,一般数据库的地址都不会做改变。
???def getCon(self): ???????try: ???????????conn=MySQLdb.connect(host=DB_Confg.Host_Sql(), ????????????????????????????????user=DB_Confg.User_sql(), ????????????????????????????????passwd=DB_Confg.Password_Sql(), ????????????????????????????????db=DB_Confg.Dbname_Sql(), ????????????????????????????????port=DB_Confg.Port_Sql(), ????????????????????????????????charset=DB_Confg.Charset_Sql()) ???????????return conn ???????except MySQLdb.Error,e: ???????????print "Mysqldb Error:%s" % e
结语:为什么用那么多的静态的方法。就是为了mysql中。不需要写长串的东西;
配置文件通过读取json方式读取
原文地址:http://www.cnblogs.com/xiaoxiao-niao/p/8017962.html