python - 在 Python 中存储简单的用户设置

标签 python database web settings

我正在编写一个网站,用户可以在其中进行多项设置,例如他们选择的配色方案等。我很乐意将这些存储为纯文本文件,安全性不是问题。

我目前的看法是:有一个字典,其中所有键都是用户,值是字典,其中包含用户的设置。

例如,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/

相关文章:

python - 使用Python+Flask实现高效的 session 变量服务器端缓存

html - 如何左右浮动 <div>

python - 在 python 中排除以下划线开头或长度超过六个字符的文件夹

python - 如何从数据框中绘制多条线

sql - 查询子查询

database - 将数据假脱机到 Excel 中的不同工作表中

html - 使用 meta http-equiv 标签重定向时避免将页面添加到浏览器历史记录

python - 狮身人面像 :ivar tag goes looking for cross-references

python - 在 Python 中读取 xml 文件

objective-c - 在 iOS 应用程序上保存数据的最有效方式