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

Ali*_*air 7 python database settings web

我正在编写一个网站,其中用户将有许多设置,例如他们选择的配色方案等.我很乐意将它们存储为纯文本文件,并且安全性不是问题.

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

例如,userdb ["bob"] ["colour_scheme"]的值为"blue".

将文件存储在文件中的最佳方法是什么?腌制字典?

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

Noa*_*oah 9

我会使用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
Run Code Online (Sandbox Code Playgroud)

请注意,ConfigParser仅支持字符串,因此您必须按照我上面的布尔值进行转换.请参阅effbot以了解基础知识.


Vin*_*vic 7

在字典上使用cPickle将是我的选择.字典很适合这类数据,因此根据您的要求,我认为没有理由不使用它们.除非您考虑从非python应用程序中读取它们,否则您必须使用语言中性文本格式.即使在这里,你也可以使用泡菜和出口工具.


Che*_*ery 6

我没有解决哪一个最好的问题.如果你想处理文本文件,我会考虑ConfigParser -module.你可以尝试的另一个是simplejsonyaml.您还可以考虑一个真正的数据库表.

例如,你可以有一个名为userattrs的表,有三列:

  • Int user_id
  • String attribute_name
  • String attribute_value

如果只有少数,您可以将它们存储到cookie中以便快速检索.


S.L*_*ott 5

这是最简单的方法。使用简单变量和import设置文件。

调用文件 userprefs.py

# a user prefs file
color = 0x010203
font = "times new roman"
position = ( 12, 13 )
size = ( 640, 480 )
Run Code Online (Sandbox Code Playgroud)

在您的应用程序中,您需要确保可以导入此文件。你有很多选择。

  1. 使用PYTHONPATH. 需要PYTHONPATH设置为包含首选项文件的目录。

    一种。用于命名文件的显式命令行参数(不是最好的,但很简单)

    湾 用于命名文件的环境变量。

  2. 扩展sys.path以包含用户的主目录

例子

import sys
import os
sys.path.insert(0,os.path.expanduser("~"))
import userprefs 
print userprefs.color
Run Code Online (Sandbox Code Playgroud)