我正在编写一个网站,用户可以在其中进行多项设置,例如他们选择的配色方案等。我很乐意将这些存储为纯文本文件,安全性不是问题。
我目前的看法是:有一个字典,其中所有键都是用户,值是字典,其中包含用户的设置。
例如,userdb["bob"]["colour_scheme"] 的值为“blue”。
将其存储在文件中的最佳方式是什么?腌制字典?
是否有更好的方法来完成我想做的事情?
最佳答案
我会使用 ConfigParser模块,它为您的示例生成一些非常易读且用户可编辑的输出:
[bob] colour_scheme: blue british: yes [joe] color_scheme: that's 'color', silly! british: no
The following code would produce the config file above, and then print it out:
import sys
from ConfigParser import *
c = ConfigParser()
c.add_section("bob")
c.set("bob", "colour_scheme", "blue")
c.set("bob", "british", str(True))
c.add_section("joe")
c.set("joe", "color_scheme", "that's 'color', silly!")
c.set("joe", "british", str(False))
c.write(sys.stdout) # this outputs the configuration to stdout
# you could put a file-handle here instead
for section in c.sections(): # this is how you read the options back in
print section
for option in c.options(section):
print "\t", option, "=", c.get(section, option)
print c.get("bob", "british") # To access the "british" attribute for bob directly
请注意,ConfigParser 仅支持字符串,因此您必须像我上面对 bool 值那样进行转换。参见 effbot了解基础知识。
关于python - 在 Python 中存储简单的用户设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/200599/