def save_local_setting_JSON(dest, content):
fwrite = open(dest, 'wb')
dict_json = eval(json.dumps(content))
string_json =json.dumps(dict(dict_json))
fwrite.write('EMAIL_DEVELOPMENT='+string_json+"\n")
fwrite.close()
def config_mail_show(request, template='admin/config_mail.html'):
form = forms.ConfigMailForm()# for for user input their mail config
context = {
'site_host' : settings.SITE_HOST,
'default_from_email' : settings.DEFAULT_FROM_EMAIL,
'email_host' : settings.EMAIL_HOST,
'email_port' : settings.EMAIL_PORT,
'email_host_user' : settings.EMAIL_HOST_USER,
'email_host_password' : settings.EMAIL_HOST_PASSWORD,
'email_use_tls' : settings.EMAIL_USE_TLS,
'form':form
}
if request.method == "POST":
form = forms.ConfigMailForm(request.method)
save_local_setting_JSON('local_setting.py', request.POST)
return render_to_response(template, context)
local_setting.py将采用以下格式:
EMAIL_DEVELOPMENT={"email_host_password": "xxxxxx", "site_host": "127.0.0.1:8000", "default_from_email": "xxx xxx <xxx@xxx.xxx>", "email_use_tls": "False", "email_port": "25","email_host_user": "xxx@xxx.xxx", "email_host": "smtp.xxx.xx"}
在settings.py中我添加了
from local_setting import *
if EMAIL_DEVELOPMENT.has_key('save'):
SITE_HOST = EMAIL_DEVELOPMENT['site_host']
DEFAULT_FROM_EMAIL = EMAIL_DEVELOPMENT['default_from_email']
EMAIL_HOST = EMAIL_DEVELOPMENT['email_host']
EMAIL_PORT =EMAIL_DEVELOPMENT['email_port']
EMAIL_HOST_USER = EMAIL_DEVELOPMENT['email_host_user']
EMAIL_HOST_PASSWORD = EMAIL_DEVELOPMENT['email_host_password']
EMAIL_USE_TLS = EMAIL_DEVELOPMENT['email_use_tls']
else:# My Development
SITE_HOST = '127.0.0.1:8000'
DEFAULT_FROM_EMAIL = 'xxxxx'
EMAIL_HOST = 'xxxxx'
EMAIL_PORT = 25
EMAIL_HOST_USER ='xxxx'
EMAIL_HOST_PASSWORD = 'xxxxx'
EMAIL_USE_TLS = False
我不确定这是使用户界面为用户提供自己的配置(例如Mail)的好方法。
这里的每个人都可以做出这样的好选择吗?
答案 0 :(得分:3)
我喜欢django-dbsettings来处理可配置的设置是运行时。
答案 1 :(得分:2)
settings.py适用于网站范围的设置。如果您希望每个用户都有自己的设置,请创建一个名为user_settings的模型(当然,使用FK到Users模型)并使用它来存储每个用户的设置。
答案 2 :(得分:1)
无论你走哪条路,它都会变成黑客 - 我保证。
那就是说,我认为你走在了正确的轨道上。将设置存储在数据库中似乎是一个坏主意,因为数据库连接设置可以在settings.py文件中找到,这可能会导致一些非常糟糕的问题。
您使用JSON并将数据存储为磁盘文件的想法可能是最好的方法,因为如果不在数据库中,它还会如何存储?
我对你试图实现这一目标的方式的唯一反应是,对这些EMAIL_HOST = EMAIL_DEVELOPMENT['email_host']
这样的所有行进行手工编码似乎真的很蹩脚。只检查本地设置JSON中是否存在该值并自动返回它会更容易。
这是一些hacky和未经测试的概念代码。将settings.py复制到settings_default.py,这将成为新的settings.py:
settings.py
from local_settings import EMAIL_DEVELOPMENT
import settings_default as defaults
import sys
class DynamicSettings(object):
def __getattr__(self, key):
if hasattr(EMAIL_DEVELOPMENT, key):
return getattr(EMAIL_DEVELOPMENT, key.lower())
else:
return getattr(defaults, key)
sys.modules[__name__] = DynamicSettings()
答案 3 :(得分:0)
也许以下内容可行:
class _DynamicMailSettings(object):
@property
def get_mail_host(self):
result = 'smtp.mydomain.com' #replace with DB query
return result
_dynamic_mail_settings = _DynamicMailSettings()
EMAIL_HOST = _dynamic_mail_settings.get_mail_host
我没有在django settings.py中测试它,但它可以在一个独立的python文件中运行。