简体   繁体   English

Django:从settings.py文件或基本配置文件导入变量是否更好?

[英]Django : is it better to import variables from a settings.py file, or basic configuration file?

I was wondering about whether it is better to import variables into your view from the settings.py file? 我想知道从settings.py文件导入变量到视图是否更好? or better to create a configuration file with the variables that are needed? 或者更好地使用所需的变量创建配置文件?

I tend to like to write configuration files for my Django applications, read, and import the variables from there when necessary. 我倾向于为我的Django应用程序编写配置文件,在必要时从那里读取和导入变量。 For example: 例如:

.configrc .configrc

[awesomeVariables]
someMagicNumber = 7

views.py views.py

from ConfigParser import SafeConfigParser
#Open and parse the file
config = SafeConfigParser()
config.read(pathToConfig)
#Get variable
magicNumber   = config.get('awesomeVariables', 'someMagicNumber'))

However , I've noticed some programmers prefer the following : 但是 ,我注意到一些程序员更喜欢以下内容:

settings.py settings.py

SOME_MAGIC_NUMBER=7

views.py views.py

import settings
magicNumber = settings.SOME_MAGIC_NUMBER

I was curious as to the pros and cons of the different methods? 我很好奇不同方法的优点和缺点? Can importing variables directly from your settings compromise the integrity of the architecture? 可以直接从您的设置导入变量会损害架构的完整性吗?

It's a judgement call. 这是一个判断电话。 Using the settings module is the "Django way", although you should do from django.conf import settings; settings.MY_SETTING 使用设置模块是“Django方式”,虽然你应该from django.conf import settings; settings.MY_SETTING from django.conf import settings; settings.MY_SETTING , which will respect DJANGO_SETTINGS_MODULE . from django.conf import settings; settings.MY_SETTING ,这将尊重DJANGO_SETTINGS_MODULE But Django is just Python; 但是Django只是Python; there's nothing that will stop you from using ConfigParser . 没有什么能阻止你使用ConfigParser In the interest of having only one place where such things are defined, I'd recommend putting it in the Django settings file - but if you have a reason not to, don't. 为了只有一个地方可以定义这样的东西,我建议把它放在Django设置文件中 - 但是如果你有理由不这样做,那就不要了。

Using a config file is completely un-Django. 使用配置文件完全不是Django。 Settings go in settings.py. 设置进入settings.py。 Period. 期。 For app-specific settings, you simply set a default in your app and allow the user to override in their project's settings.py: 对于特定于应用程序的设置,您只需在应用程序中设置默认值,并允许用户在其项目的settings.py中覆盖:

from django.conf import settings

SOME_MAGIC_NUMBER = settings.SOME_MAGIC_NUMBER if hasattr(settings, 'SOME_MAGIC_NUMBER') else 0
# Where `0` is the default value

There also an app for storing settings dynamically in db. 还有一个用于在db中动态存储设置的应用程序。 Maybe you find it usefull . 也许你觉得它很有用。 django-constance Django的康斯坦斯

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

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