在 Python 中存储简单的用户设置
我正在编写一个网站,其中用户将有许多设置,例如他们选择的配色方案等。我很乐意将这些存储为纯文本文件,并且安全性不是问题。
我目前看到的方式是:有一个字典,其中所有键都是用户,值是包含用户设置的字典。
例如,userdb["bob"]["colour_scheme"] 的值为“blue”。
将其存储在文件中的最佳方式是什么? 腌制字典?
有更好的方法来做我想做的事情吗?
I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.
The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.
For example, userdb["bob"]["colour_scheme"] would have the value "blue".
What is the best way to store it on file? Pickling the dictionary?
Are there better ways of doing what I am trying to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
我同意关于使用 Pickled Dictionary 的回复。 对于在字典结构中存储简单数据非常简单有效。
I agree with the reply about using Pickled Dictionary. Very simple and effective for storing simple data in a Dictionary structure.
如果您不关心自己能否编辑文件,并且想要一种快速保存 python 对象的方法,请使用 pickle。 如果您确实希望该文件可供人类读取或由其他应用程序读取,请使用 ConfigParser。 如果您需要更复杂的内容,请使用某种数据库,无论是关系型数据库(sqlite),或面向对象的 (公理, zodb)。
If you don't care about being able to edit the file yourself, and want a quick way to persist python objects, go with pickle. If you do want the file to be readable by a human, or readable by some other app, use ConfigParser. If you need anything more complex, go with some sort of database, be it relational (sqlite), or object-oriented (axiom, zodb).
我会使用 ConfigParser 模块,它会产生一些漂亮的您的示例的可读且用户可编辑的输出:
以下代码将生成上面的配置文件,然后将其打印出来:
请注意,ConfigParser 仅支持字符串,因此您必须像我上面对布尔值所做的那样进行转换。 请参阅 effbot 了解基础知识的详细概述。
I would use the ConfigParser module, which produces some pretty readable and user-editable output for your example:
The following code would produce the config file above, and then print it out:
Note that ConfigParser only supports strings, so you'll have to convert as I have above for the Booleans. See effbot for a good run-down of the basics.
在字典上使用 cPickle 将是我的选择。 字典非常适合此类数据,因此鉴于您的要求,我认为没有理由不使用它们。 除非您正在考虑从非 python 应用程序中读取它们,在这种情况下您必须使用语言中性的文本格式。 即使在这里,您也可以使用 pickle 和导出工具。
Using cPickle on the dictionary would be my choice. Dictionaries are a natural fit for these kind of data, so given your requirements I see no reason not to use them. That, unless you are thinking about reading them from non-python applications, in which case you'd have to use a language neutral text format. And even here you could get away with the pickle plus an export tool.
我不会解决哪一个最好的问题。 如果你想处理文本文件,我会考虑 ConfigParser -模块。 您可以尝试的另一个方法是 simplejson 或 yaml. 您还可以考虑真正的数据库表。
例如,您可以有一个名为 userattrs 的表,其中包含三列:
如果只有很少的列,您可以将它们存储到 cookie 中以便快速检索。
I don't tackle the question which one is best. If you want to handle text-files, I'd consider ConfigParser -module. Another you could give a try would be simplejson or yaml. You could also consider a real db table.
For instance, you could have a table called userattrs, with three columns:
If there's only few, you could store them into cookies for quick retrieval.
这是最简单的方法。 使用简单变量并
导入
设置文件。调用文件 userprefs.py
在您的应用程序中,您需要确保可以导入该文件。 您有很多选择。
使用
PYTHONPATH
。 需要设置PYTHONPATH
以包含包含首选项文件的目录。a. 用于命名文件的显式命令行参数(不是最好的,但简单)
b. 用于命名文件的环境变量。
扩展
sys.path
以包含用户的主目录示例
Here's the simplest way. Use simple variables and
import
the settings file.Call the file userprefs.py
In your application, you need to be sure that you can import this file. You have many choices.
Using
PYTHONPATH
. RequirePYTHONPATH
be set to include the directory with the preferences files.a. An explicit command-line parameter to name the file (not the best, but simple)
b. An environment variable to name the file.
Extending
sys.path
to include the user's home directoryExample
对于数据库驱动的网站,当然,最好的选择是数据库表。 我假设你没有做数据库的事情。
如果您不关心人类可读的格式,那么
pickle
是一种简单直接的方法。 我还听说过有关simplejson
的好报道。如果人类可读性很重要,那么有两个简单的选择:
模块: 仅使用模块。 如果您需要的只是一些全局变量并且没有什么花哨的东西,那么这就是要走的路。 如果你真的绝望了,你可以定义类和类变量来模拟节。 这里的缺点是:如果文件由用户手动编辑,则错误可能很难捕获和调试。
INI 格式: 我一直在使用 ConfigObj为此,取得了相当大的成功。 ConfigObj 本质上是 ConfigParser 的替代品,支持嵌套部分等等。 或者,您可以定义文件的预期类型或值并验证它,为用户/管理员提供安全网(和重要的错误反馈)。
For a database-driven website, of course, your best option is a db table. I'm assuming that you are not doing the database thing.
If you don't care about human-readable formats, then
pickle
is a simple and straightforward way to go. I've also heard good reports aboutsimplejson
.If human readability is important, two simple options present themselves:
Module: Just use a module. If all you need are a few globals and nothing fancy, then this is the way to go. If you really got desperate, you could define classes and class variables to emulate sections. The downside here: if the file will be hand-edited by a user, errors could be hard to catch and debug.
INI format: I've been using ConfigObj for this, with quite a bit of success. ConfigObj is essentially a replacement for ConfigParser, with support for nested sections and much more. Optionally, you can define expected types or values for a file and validate it, providing a safety net (and important error feedback) for users/administrators.
我会使用 shelve 或 sqlite 数据库(如果我必须将这些设置存储在文件系统上) 。 虽然,既然您正在构建一个网站,您可能会使用某种数据库,那么为什么不直接使用它呢?
I would use shelve or an sqlite database if I would have to store these setting on the file system. Although, since you are building a website you probably use some kind of database so why not just use that?
内置的 sqlite3 模块可能会很远比大多数替代方案更简单,并且可以让您准备好更新到完整的 RDBMS(如果您愿意或需要)。
The built-in sqlite3 module would probably be far simpler than most alternatives, and gets you ready to update to a full RDBMS should you ever want or need to.
如果配置文件的人类可读性很重要,替代方案可能是 ConfigParser 模块允许您读取和写入 .ini 之类的文件。 但这样一来,您就被限制为一层嵌套。
If human readablity of configfiles matters an alternative might be the ConfigParser module which allows you to read and write .ini like files. But then you are restricted to one nesting level.
如果您有数据库,我可能建议将设置存储在数据库中。 但是,听起来普通文件可能更适合您的环境。
您可能不想将所有用户设置存储在同一个文件中,因为您可能会在并发访问该文件时遇到麻烦。 如果您将每个用户的设置作为字典存储在他们自己的腌制文件中,那么他们将能够独立操作。
Pickling 是存储此类数据的合理方法,但不幸的是,pickle 数据格式众所周知不可读。 您最好将其存储为
repr(dictionary)
,这将是一种更具可读性的格式。 要重新加载用户设置,请使用eval(open("file").read())
或类似的东西。If you have a database, I might suggest storing the settings in the database. However, it sounds like ordinary files might suit your environment better.
You probably don't want to store all the users settings in the same file, because you might run into trouble with concurrent access to that one file. If you stored each user's settings as a dictionary in their own pickled file, then they would be able to act independently.
Pickling is a reasonable way to store such data, but unfortunately the pickle data format is notoriously not-human-readable. You might be better off storing it as
repr(dictionary)
which will be a more readable format. To reload the user settings, useeval(open("file").read())
or something like that.您不使用数据库是否有特殊原因? 这似乎是正常和自然的事情 - 或者将设置的 pickle 存储在数据库中,并以用户 ID 或其他方式键入。
您没有描述网站的使用模式,而只是考虑一个一般网站 - 但我认为将设置保留在数据库中会比使用文件导致更少的磁盘 I/O。
OTOH,对于客户端代码可能使用的设置,将它们作为 javascript 存储在可以缓存的静态文件中会很方便 - 代价是在多个位置可能有设置。 (我可能会将这些设置存储在数据库中,并根据需要重建静态文件)
Is there are particular reason you're not using the database for this? it seems the normal and natural thing to do - or store a pickle of the settings in the db keyed on user id or something.
You haven't described the usage patterns of the website, but just thinking of a general website - but I would think that keeping the settings in a database would cause much less disk I/O than using files.
OTOH, for settings that might be used by client-side code, storing them as javascript in a static file that can be cached would be handy - at the expense of having multiple places you might have settings. (I'd probably store those settings in the db, and rebuild the static files as necessary)