c228416809
- kfet_config gives "reduction_cof" as editable instead of "subvention_cof" - this last one can still be accessed via kfet_config (computed from new "reduction_cof" - add units to numeric values of kfet_config form
71 lines
2 KiB
Python
71 lines
2 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
from django.core.exceptions import ValidationError
|
|
from django.db import models
|
|
|
|
from djconfig import config
|
|
|
|
|
|
class KFetConfig(object):
|
|
"""kfet app configuration.
|
|
|
|
Enhance isolation with backend used to store config.
|
|
Usable after DjConfig middleware was called.
|
|
|
|
"""
|
|
prefix = 'kfet_'
|
|
|
|
def __getattr__(self, key):
|
|
if key == 'subvention_cof':
|
|
# Allows accessing to the reduction as a subvention
|
|
# Other reason: backward compatibility
|
|
reduction_mult = 1 - self.reduction_cof/100
|
|
return (1/reduction_mult - 1) * 100
|
|
return getattr(config, self._get_dj_key(key))
|
|
|
|
def list(self):
|
|
"""Get list of kfet app configuration.
|
|
|
|
Returns:
|
|
(key, value) for each configuration entry as list.
|
|
|
|
"""
|
|
# prevent circular imports
|
|
from kfet.forms import KFetConfigForm
|
|
return [(field.label, getattr(config, name), )
|
|
for name, field in KFetConfigForm.base_fields.items()]
|
|
|
|
def _get_dj_key(self, key):
|
|
return '{}{}'.format(self.prefix, key)
|
|
|
|
def set(self, **kwargs):
|
|
"""Update configuration value(s).
|
|
|
|
Args:
|
|
**kwargs: Keyword arguments. Keys must be in kfet config.
|
|
Config entries are updated to given values.
|
|
|
|
"""
|
|
# prevent circular imports
|
|
from kfet.forms import KFetConfigForm
|
|
|
|
# get old config
|
|
new_cfg = KFetConfigForm().initial
|
|
# update to new config
|
|
for key, value in kwargs.items():
|
|
dj_key = self._get_dj_key(key)
|
|
if isinstance(value, models.Model):
|
|
new_cfg[dj_key] = value.pk
|
|
else:
|
|
new_cfg[dj_key] = value
|
|
# save new config
|
|
cfg_form = KFetConfigForm(new_cfg)
|
|
if cfg_form.is_valid():
|
|
cfg_form.save()
|
|
else:
|
|
raise ValidationError(
|
|
'Invalid values in kfet_config.set: %(fields)s',
|
|
params={'fields': list(cfg_form.errors)})
|
|
|
|
|
|
kfet_config = KFetConfig()
|