简体   繁体   English

将settings.py配置文件加载到dict中

[英]Loading settings.py config file into a dict

Say I have a file called settings.py and it's content is the following: 假设我有一个名为settings.py的文件,其内容如下:

{
    "translate_tabs_to_spaces": True,
    "word_wrap": "true",
    "font_face": "Monaco",
    "font_size": 14.0,
    "highlight_line": True,
    "ignored_packages":
    [
        ""
    ],
    "what": '''
            This is python file, not json
            '''
}

How can I get it into a dict called settings in my main app file app.py? 如何在主应用程序文件app.py中将其设置为名为settings的dict?

Thanks. 谢谢。

Why not name that dict say settings and than just import it from settings.py eg 为什么不命名dict说settings而不是从settings.py导入它,例如

settings.py settings.py

settings = {} # fill with your data

use it like this 像这样使用它

>>> from settings import settings
>>> print settings
{}

Alternate solutions is to just add variables at settings module level and use them directly, why you need a dict? 替代解决方案是在设置模块级别添加变量并直接使用它们,为什么需要dict? eg 例如

settings.py settings.py

translate_tabs_to_spaces = True
# more settings

use it like this 像这样使用它

>>> import settings
>>> settings.translate_tabs_to_spaces
True

You can use ast.literal_eval() to do this safely. 您可以使用ast.literal_eval()来安全地执行此操作。

import ast

data="""\
{
    "translate_tabs_to_spaces": True,
    "word_wrap": "true",
    "font_face": "Monaco",
    "font_size": 14.0,
    "highlight_line": True,
    "ignored_packages":
    [
        ""
    ],
    "what": '''
            This is python file, not json
            '''
}\
"""

print(ast.literal_eval(data))

Giving us: 给我们:

{'what': '\n            This is python file, not json\n            ', 'font_size': 14.0, 'translate_tabs_to_spaces': True, 'font_face': 'Monaco', 'word_wrap': 'true', 'highlight_line': True, 'ignored_packages': ['']}

Edit: 编辑:

Given the new comment from the asker that suggests that he wants to be able to use ... in his config, ast.literal_eval() will not be suitable, as it can't handle ellipses. 鉴于提问者的新评论暗示他希望能够在他的配置中使用...ast.literal_eval()适合,因为它无法处理省略号。 It's not quite clear if this is what he meant, and this is still a good answer to the question that was asked. 目前尚不清楚这是否是他的意思,这仍然是对所提问题的一个很好的答案。

Turns out the asker was talking about triple quoted strings, which are handled by this correctly. 事实证明提问者正在谈论三重引用字符串,这是正确处理的。

Give the settings dict a name in the settings module then import the settings module into your module and load it into a variable like 在设置模块中为设置输入一个名称,然后将设置模块导入模块并将其加载到变量中

import settings
your_settings = settings.settings_dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM