[英]ConfigParser - Writing to .ini file
I have a config.ini file that has some default configuration for a web app (Flask using VS 2017) 我有一个config.ini文件,它有一个Web应用程序的默认配置(使用VS 2017的Flask)
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
: 我使用下面的代码尝试写入
[keys]
部分,变量是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: 我想问一个问题:
Yes, storing configuration on .ini
files is common practice, among many other possible solutions. 是的,在
.ini
文件上存储配置是常见的做法,在许多其他可能的解决方案中。 As for safety, I strongly recommend storing it on a non-public folder, somewhere outside your web root tree. 至于安全性,我强烈建议将其存储在Web公共树根之外的非公共文件夹中。 This way your Python app can read it, but no web user can download it.
这样您的Python应用程序就可以读取它,但没有Web用户可以下载它。
About your error: .ini
option values (and options names) must be strings, so change your line: 关于您的错误:
.ini
选项值(和选项名称) 必须是字符串,因此请更改您的行:
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()
然后使用configparser的
.getboolean()
而不是.get()
读取该值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.