分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

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

发布时间:2023-09-06 01:29责任编辑:彭小芳关键词:jsjson配置
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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved