在Python中存储简单用户设置

9 投票
12 回答
11009 浏览
提问于 2025-04-11 09:32

我正在编写一个网站,用户可以设置一些选项,比如选择颜色主题等等。我觉得把这些设置存成普通的文本文件就可以了,安全性不是问题。

我现在的想法是:有一个字典,字典的每个键是用户的名字,而对应的值是另一个字典,里面存着用户的设置。

举个例子,userdb["bob"]["colour_scheme"] 这个地方会存着值 "blue",也就是“蓝色”。

那么,存储这些数据到文件的最好方法是什么呢?是把这个字典“打包”存储吗?

有没有更好的方法来实现我想做的事情呢?

相关问题:

12 个回答

6

我不想讨论哪个是最好的选择。如果你想处理文本文件,我建议你看看ConfigParser模块。另外,你也可以试试simplejson或者yaml。你还可以考虑使用真正的数据库表。

比如,你可以创建一个叫做userattrs的表,里面有三列:

  • 整型的user_id
  • 字符串的attribute_name
  • 字符串的attribute_value

如果数据不多,你可以把它们存储在cookies里,这样可以快速取用。

10

我会使用ConfigParser模块,这个模块能生成一些比较易读且用户可以编辑的输出,适合你的例子:

[bob]
colour_scheme: blue
british: yes
[joe]
color_scheme: that's 'color', silly!
british: no

下面的代码会生成上面的配置文件,然后把它打印出来:

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只支持字符串,所以你需要像我上面那样把布尔值转换一下。想了解基础知识,可以参考effbot

7

我会选择在字典上使用 cPickle。字典非常适合这类数据,所以根据你的需求,我觉得没有理由不使用它们。除非你考虑从非Python的应用程序中读取这些数据,那样的话你就需要使用一种不依赖于语言的文本格式。不过即使在这种情况下,你也可以使用pickle加上一个导出工具来解决问题。

撰写回答