Where to store settings in Django application?
I want to be able to change some of the settings defined in settings.py file in run time. The changes should also be kept (after server restart). I found https://开发者_开发百科github.com/jabapyth/django-appsettings but it lacks support for arrays and tuples. Is there something better?
Settings are not meant to be changed at runtime.
Doing this could lead to threading issues and inconsistencies, as they are loaded at the start by each worker upon initialization, so you change them in one process and the others don't have the updated value.
https://docs.djangoproject.com/en/dev/topics/settings/#altering-settings-at-runtime
Edit
If you manage to store those settings into the data model, you can take advantage of the low-level cache system, so almost no query happens until data is changed and you invalidate those values manually. See https://docs.djangoproject.com/en/1.3//topics/cache/#the-low-level-cache-api .
Edit 2
You can add a very simple and generic setting model, and manage it through the admin interface or whatever.
class Setting(models.Model):
name = models.CharField(max_length=100)
value = models.CharField(max_length=500)
value_type = models.CharField(max_length=1, choices=(('s','string'),('i','integer'),('b','boolean'))
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
def actual_value(self):
types = {
's': str,
'i':int,
'b': (lambda v: v.lower().startswith('t') or v.startswith('1'))
}
return types[self.value_type](self.value)
For site-wide settings, attach to a Site model, for User-specific setting, attach to a User etc.
Edit 3
You can use Manager objects to return lists or dicts:
class SettingManager(models.Manager):
def dict_for_object(self, object):
ct = ContentType.get_for_model(object)
pk = object.pk
return dict(self.filter(object_id=pk, content_type__id=ct.id).values_list('name', 'value'))
精彩评论