简体   繁体   中英

ConfigParser - Writing to .ini file

I have a config.ini file that has some default configuration for a web app (Flask using VS 2017)

I also want to write some configuration myself.

I am using the below code to try to write in the [keys] section, the variable being gkey :

def writeKey(key):
    Config = configparser.ConfigParser()    
    configFile = Path("config.ini")
    if configFile.is_file() == False:
        cfgfile = open("config.ini",'w')
    else:
        cfgfile = open("config.ini")

    # add the settings to the structure of the file, and lets write it out...
    Config.add_section('keys')
    Config.set('gkey','key',True)
    Config.write(cfgfile)
    cfgfile.close()

gkey = encrypt(key)
writeKey(gkey)

I get the below error:

Traceback (most recent call last):
  File "C:\Users\blivo\documents\visual studio 2017\Projects\blivori2\blivori2\blivori2\functions\common.py", line 59, in <module>
    writeKey(gkey)
  File "C:\Users\blivo\documents\visual studio 2017\Projects\blivori2\blivori2\blivori2\functions\common.py", line 30, in writeKey
    Config.set('gkey','key',True)
  File "C:\Program Files\Python36\lib\configparser.py", line 1189, in set
    self._validate_value_types(option=option, value=value)
  File "C:\Program Files\Python36\lib\configparser.py", line 1174, in _validate_value_types
    raise TypeError("option values must be strings")
TypeError: option values must be strings

I would like to ask a question:

  • Would it be appropriate to store configuration in an .ini file? If so, how is the best way to protect it from being read/exposed to the public.

Yes, storing configuration on .ini files is common practice, among many other possible solutions. As for safety, I strongly recommend storing it on a non-public folder, somewhere outside your web root tree. This way your Python app can read it, but no web user can download it.

About your error: .ini option values (and options names) must be strings, so change your line:

Config.set('gkey','key',True)

to

Config.set('gkey','key','True')  # or '0'

And then read that value using configparser's .getboolean() instead of .get()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM