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中。不需要寫長串的東西;
疑問解答QQ群:群1:588402570,群2 772588688
群1 限制人數后,請申請群2
關注該公眾號:持續更新Jmeter相關內容