• python ConfigParser 小试


    由于工作需要,需要将数据库的int型数据转换成string类型放到页面上,并从页面上拿回string类型转换成可以作为sql查询参数的int型数据。注,这个string类型的字串和int型数据纯属于人工自定义的编码行为,因此需要用到config文件。

    查到python有ConfigParser,这个还蛮好用的,赶紧试了一下:

    1.设计config文件:config.cfg,文件分为很多个section,每个section包含很多对key-value;如下:

      

    [server type]
    1= App Server
    2= WriteBack Server
    3= Memcache Server
    4= Database Server
    
    [server status]
    0= added
    1= monitored
    2= crashed
    3= deleted
    4= alerted
    
    [alert type]
    1= email alert
    2= sms alert
    
    [server monitor status]
    0= Alert
    1= Don't Alert

    2.读取配置文件:

    def readConfig(type, value='1'):
        config = ConfigParser.ConfigParser()
        #type = "ServerStatus"
        value = str(value)
        try:
            with open("./static/data/config.cfg","r") as cfgfile:
                config.readfp(cfgfile)
                if type == "ServerType":
                    items = dict(config.items('server type'))
                elif type == "ServerStatus":
                    items = dict(config.items('server status'))
                elif type == "AlertType":
                    items = dict(config.items('alert type'))
                elif type == "MonitorStatus":
                    items = dict(config.items('server monitor status'))
                data = items[value]
                print data
                return data
        except Exception:
            print 'error in readConfig when setting new host string by config file'
    

      在每次从数据库取到数据时,调用这个readConfig方法将拿到的数据进行config成string,再传到页面进行显示。结果很顺利!

    但是问题也随之来了,我还要从页面上拿回这个String传到后台作为取数据的sql参数,但是这个与数据库毫无关系的string如何转换成int呢?我想了一个dconfig,就是反config回来啦!但是蹊跷的是,同样的方法,却得到了一个int() argument must be a string or a number, not 'NoneType'的错误,于是查找定位到我在初始化value这个参数的时候传了一个空串,然后被当做None,int(None)是不被接受的。改掉,依旧不行。打印传回来的参数:

    alerted
    App Server

    于是做了个小测试,发现alerted能找到它的对应值,但是App Server找不到,改成小写的’app server‘结果又找到了,真是坑爹,去看下文档有没有说明不接受大写字符串,或者是有存在编码问题?

    最后将config的文件里全改成小写,做测试,好莫名其妙啊!打印出来竟然还是:

    alerted
    App Server

    Why??明明文件已经保存了!难道这cfg文件是要缓存到客户端里的?不可能,明明是后台调用的,好吧,我把你删掉再建一个,放进去小写,重启动。ok了!这次变小些了,只是页面上显示的还是小写的,未必符合要求。

    ConfigParser是个好东西,python的库就是封装的好啊!关于config的事情,如果没有特殊要求,基本上够用啦。。。。

    忽然想到一个事情,我这典型的交互和需要config的次数太多,我为啥不考虑把config的一个key-value都传到客户端嗯?再客户端显示的时候用string的value,返回查询用的int的key,岂不是一举两得?

  • 相关阅读:
    POJ 2000 Gold Coins
    HDU 5804 Price List
    POJ 1316 Self Numbers
    HDU 5783 Divide the Sequence
    rabbitmq基础使用
    centos7安装RabbitMQ
    编程之路┊一个程序员走过的路
    jquery layer弹出层插件
    SWFUpload 2.5.0版 官方说明文档 中文翻译版
    C# 格式化字符串,日期,字符串操作汇总
  • 原文地址:https://www.cnblogs.com/xiami303/p/2653922.html
Copyright © 2020-2023  润新知