ConfigParser - Writing to .ini file

configparser, flask, python

Solution

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 '1'

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

Also, I strongly advise against using `open()` without a `with ...` block. And it seems there's no good reason for the `if` tests, it's considered an anti-pattern and poor programming practice in Python. The code could be made simpler and more robust using the standard pattern:

def writeKey(key):
    with open("config.ini", 'w') as cfgfile:
        Config = configparser.ConfigParser()    
        # add the settings to the structure of the file, and lets write it out...
        Config['keys']['gkey'] = key
        Config.write(cfgfile)

Problem

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.

Original source