码迷,mamicode.com
首页 > Web开发 > 详细

配置文件通过读取json方式读取

时间:2017-12-10 21:40:45      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:self   char   方法   mysql   打印   pass   内容   red   就是   

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 json

load 将文件中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的类型



jump
with open(‘‘c:\test.json","w") as d:
      check = json.dump(a)#写入json中


将配置文件中读取的内容。使用静态的方式显示
import os,json,logger

class 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 MySQLdb
from 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方式读取

标签:self   char   方法   mysql   打印   pass   内容   red   就是   

原文地址:http://www.cnblogs.com/xiaoxiao-niao/p/8017962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!