Exemple #1
0
        def get_config(self, group, key):
            try:
                if isinstance(group, values.ConfigurationGroup):
                    group = group.key

                cg = self.settings.get(group, None)
                if not cg:
                    raise SettingNotSet('%s config group does not exist' % group)

                else:
                    return cg[key]
            except KeyError:
                raise SettingNotSet('%s.%s' % (group, key))
Exemple #2
0
 def load_module(self, module):
     """Load a child module"""
     value = self._value()
     if value == NOTSET:
         raise SettingNotSet("%s.%s", self.group.key, self.key)
     else:
         return load_module("%s.%s" % (value, module))
Exemple #3
0
    def _value(self):
        use_db, overrides = get_overrides()

        if not use_db:
            try:
                val = overrides[self.group.key][self.key]
            except KeyError:
                if self.use_default:
                    val = self.default
                else:
                    raise SettingNotSet(
                        '%s.%s is not in your LIVESETTINGS_OPTIONS' %
                        (self.group.key, self.key))

        else:
            try:
                val = self.setting.value

            except SettingNotSet, sns:
                if self.use_default:
                    val = self.default
                    if overrides:
                        # maybe override the default
                        grp = overrides.get(self.group.key, {})
                        if grp.has_key(self.key):
                            val = grp[self.key]
                else:
                    val = NOTSET

            except AttributeError, ae:
                log.error("Attribute error: %s", ae)
                log.error("%s: Could not get _value of %s", self.key,
                          self.setting)
                raise (ae)
Exemple #4
0
def config_collect_values(group,
                          groupkey,
                          key,
                          unique=True,
                          skip_missing=True):
    """Look up (group, groupkey) from config, then take the values returned and
    use them as groups for a second-stage lookup.

    For example:

    config_collect_values(PAYMENT, MODULES, CREDITCHOICES)

    Stage 1: ['PAYMENT_GOOGLE', 'PAYMENT_AUTHORIZENET']
    Stage 2: config_value('PAYMENT_GOOGLE', 'CREDITCHOICES')
           + config_value('PAYMENT_AUTHORIZENET', 'CREDITCHOICES')
    Stage 3: (if unique is true) remove dupes
    """
    groups = config_value(group, groupkey)

    ret = []
    for g in groups:
        try:
            ret.append(config_value(g, key))
        except KeyError, ke:
            if not skip_missing:
                raise SettingNotSet('No config %s.%s' % (g, key))
Exemple #5
0
    def _value(self):
        use_db, overrides = get_overrides()

        lang = get_language()

        key = self.key
        if self.localized:
            key += '_' + format_setting_name(lang)

        if not use_db:
            try:
                val = overrides[self.group.key][key]
            except KeyError:
                if self.use_default:
                    val = self.default
                else:
                    raise SettingNotSet(
                        '%s.%s is not in your LIVESETTINGS_OPTIONS' %
                        (self.group.key, key))

        else:
            try:
                val = self.setting.value

            except SettingNotSet, sns:

                if self.localized and lang == django_settings.LANGUAGE_CODE:
                    try:
                        unlocalized_setting = find_setting(
                            self.group.key, self.key)
                        return unlocalized_setting.value
                    except SettingNotSet:
                        pass

                if self.use_default:
                    val = self.default
                    if overrides:
                        # maybe override the default
                        grp = overrides.get(self.group.key, {})
                        if grp.has_key(key):
                            val = grp[self.key]
                else:
                    val = NOTSET

            except AttributeError, ae:
                log.error("Attribute error: %s", ae)
                log.error("%s: Could not get _value of %s", key, self.setting)
                raise (ae)
Exemple #6
0
def config_choice_values(group, key, skip_missing=True, translate=False):
    """Get pairs of key, label from the setting."""
    try:
        cfg = config_get(group, key)
        choices = cfg.choice_values

    except SettingNotSet:
        if skip_missing:
            return []
        else:
            raise SettingNotSet('%s.%s' % (group, key))

    if translate:
        choices = [(k, ugettext(v)) for k, v in choices]

    return choices
Exemple #7
0
class Value(object):

    creation_counter = 0

    def __init__(self, group, key, **kwargs):
        """
        Create a new Value object for configuration.

        Args:
            - `ConfigurationGroup`
            - key - a string key

        Named arguments:
            - `description` - Will be passed to the field for form usage.  Should be a translation proxy.  Ex: _('example')
            - `help_text` - Will be passed to the field for form usage.
            - `choices` - If given, then the form field will use a select box
            - `ordering` - Defaults to alphabetical by key if not given.
            - `requires` - If given as a `Value`, then this field will only be rendered if that Value evaluates true (for Boolean requires) or the proper key is in the associated value.
            - `requiresvalue` - If set, then this field will only be rendered if that value is in the list returned by self.value. Defaults to self.key.
            - `hidden` - If true, then render a hidden field.
            - `default` - If given, then this Value will return that default whenever it has no assocated `Setting`.
            - `update_callback` - if given, then this value will call the callback whenever updated
        """
        self.group = group
        self.key = key
        self.description = kwargs.get('description', None)
        self.help_text = kwargs.get('help_text')
        self.choices = kwargs.get('choices', [])
        self.ordering = kwargs.pop('ordering', 0)
        self.hidden = kwargs.pop('hidden', False)
        self.update_callback = kwargs.pop('update_callback', None)
        self.requires = kwargs.pop('requires', None)
        if self.requires:
            reqval = kwargs.pop('requiresvalue', key)
            if not is_list_or_tuple(reqval):
                reqval = (reqval, reqval)

            self.requires_value = reqval[0]
            self.requires.add_choice(reqval)

        elif group.requires:
            self.requires = group.requires
            self.requires_value = group.requires_value

        if kwargs.has_key('default'):
            self.default = kwargs.pop('default')
            self.use_default = True
        else:
            self.use_default = False

        self.creation_counter = Value.creation_counter
        Value.creation_counter += 1

    def __cmp__(self, other):
        return cmp((self.ordering, self.description, self.creation_counter),
                   (other.ordering, other.description, other.creation_counter))

    def __eq__(self, other):
        if type(self) == type(other):
            return self.value == other.value
        else:
            return self.value == other

    def __iter__(self):
        return iter(self.value)

    def __unicode__(self):
        return unicode(self.value)

    def __str__(self):
        return str(self.value)

    def add_choice(self, choice):
        """Add a choice if it doesn't already exist."""
        if not is_list_or_tuple(choice):
            choice = (choice, choice)
        skip = False
        for k, v in self.choices:
            if k == choice[0]:
                skip = True
                break
        if not skip:
            self.choices += (choice, )

    def choice_field(self, **kwargs):
        if self.hidden:
            kwargs['widget'] = forms.MultipleHiddenInput()
        return forms.ChoiceField(choices=self.choices, **kwargs)

    def _choice_values(self):
        choices = self.choices
        vals = self.value
        return [x for x in choices if x[0] in vals]

    choice_values = property(fget=_choice_values)

    def copy(self):
        new_value = self.__class__(self.key)
        new_value.__dict__ = self.__dict__.copy()
        return new_value

    def _default_text(self):
        if not self.use_default:
            note = ""
        else:
            if self.default == "":
                note = _('Default value: ""')

            elif self.choices:
                work = []
                for x in self.choices:
                    if x[0] in self.default:
                        work.append(smart_str(x[1]))
                note = gettext('Default value: ') + ", ".join(work)

            else:
                note = _("Default value: %s") % unicode(self.default)

        return note

    default_text = property(fget=_default_text)

    def enabled(self):
        enabled = False
        try:
            if not self.requires:
                enabled = True
            else:
                v = self.requires.value
                if self.requires.choices:
                    enabled = self.requires_value == v or self.requires_value in v
                elif v:
                    enabled = True
        except SettingNotSet:
            pass
        return enabled

    def make_field(self, **kwargs):
        if self.choices:
            if self.hidden:
                kwargs['widget'] = forms.MultipleHiddenInput()
            field = self.choice_field(**kwargs)
        else:
            if self.hidden:
                kwargs['widget'] = forms.HiddenInput()
            field = self.field(**kwargs)

        field.group = self.group
        field.default_text = self.default_text
        return field

    def make_setting(self, db_value):
        log.debug('new setting %s.%s', self.group.key, self.key)
        return Setting(group=self.group.key, key=self.key, value=db_value)

    def _setting(self):
        return find_setting(self.group.key, self.key)

    setting = property(fget=_setting)

    def _value(self):
        use_db, overrides = get_overrides()

        if not use_db:
            try:
                val = overrides[self.group.key][self.key]
            except KeyError:
                if self.use_default:
                    val = self.default
                else:
                    raise SettingNotSet(
                        '%s.%s is not in your LIVESETTINGS_OPTIONS' %
                        (self.group.key, self.key))

        else:
            try:
                val = self.setting.value

            except SettingNotSet, sns:
                if self.use_default:
                    val = self.default
                    if overrides:
                        # maybe override the default
                        grp = overrides.get(self.group.key, {})
                        if grp.has_key(self.key):
                            val = grp[self.key]
                else:
                    val = NOTSET

            except AttributeError, ae:
                log.error("Attribute error: %s", ae)
                log.error("%s: Could not get _value of %s", self.key,
                          self.setting)
                raise (ae)

            except Exception, e:
                global _WARN
                log.error(e)
                if str(e).find("configuration_setting") > -1:
                    if not _WARN.has_key('configuration_setting'):
                        log.warn(
                            'Error loading setting %s.%s from table, OK if you are in syncdb',
                            self.group.key, self.key)
                        _WARN['configuration_setting'] = True

                    if self.use_default:
                        val = self.default
                    else:
                        raise ImproperlyConfigured(
                            "All settings used in startup must have defaults, %s.%s does not",
                            self.group.key, self.key)
                else:
                    import traceback
                    traceback.print_exc()
                    log.warn("Problem finding settings %s.%s, %s",
                             self.group.key, self.key, e)
                    raise SettingNotSet("Startup error, couldn't load %s.%s" %
                                        (self.group.key, self.key))
Exemple #8
0
class Value(object):

    creation_counter = 0

    def __init__(self, group, key, **kwargs):
        """
        Create a new Value object for configuration.

        Args:
            - `ConfigurationGroup`
            - key - a string key

        Named arguments:
            - `description` - Will be passed to the field for form usage.  Should be a translation proxy.  Ex: _('example')
            - `help_text` - Will be passed to the field for form usage.
            - `choices` - If given, then the form field will use a select box
            - `ordering` - Defaults to alphabetical by key if not given.
            - `requires` - If given as a `Value`, then this field will only be rendered if that Value evaluates true (for Boolean requires) or the proper key is in the associated value.
            - `requiresvalue` - If set, then this field will only be rendered if that value is in the list returned by self.value. Defaults to self.key.
            - `hidden` - If true, then render a hidden field.
            - `default` - If given, then this Value will return that default whenever it has no assocated `Setting`.
            - `update_callback` - if given, then this value will call the callback whenever updated
            - `clear_cache` - if `True` - clear all the caches on updates
        """
        self.group = group
        self.key = key
        self.description = kwargs.get('description', None)
        self.help_text = kwargs.get('help_text')
        self.choices = kwargs.get('choices',[])
        self.ordering = kwargs.pop('ordering', 0)
        self.hidden = kwargs.pop('hidden', False)
        self.localized = kwargs.pop('localized', False)
        self.update_callback = kwargs.pop('update_callback', None)
        self.requires = kwargs.pop('requires', None)
        self.clear_cache = kwargs.pop('clear_cache', False)
        if self.requires:
            reqval = kwargs.pop('requiresvalue', key)
            if not is_list_or_tuple(reqval):
                reqval = (reqval, reqval)

            self.requires_value = reqval[0]
            self.requires.add_choice(reqval)

        elif group.requires:
            self.requires = group.requires
            self.requires_value = group.requires_value

        if kwargs.has_key('default'):
            self.default = kwargs.pop('default')
            self.use_default = True
        else:
            self.use_default = False

        self.creation_counter = Value.creation_counter
        Value.creation_counter += 1

    def __cmp__(self, other):
        return cmp((self.ordering, self.description, self.creation_counter), (other.ordering, other.description, other.creation_counter))

    def __eq__(self, other):
        if type(self) == type(other):
            return self.value == other.value
        else:
            return self.value == other

    def __iter__(self):
        return iter(self.value)

    def __unicode__(self):
        return unicode(self.value)

    def __str__(self):
        return str(self.value)

    def add_choice(self, choice):
        """Add a choice if it doesn't already exist."""
        if not is_list_or_tuple(choice):
            choice = (choice, choice)
        skip = False
        for k, v in self.choices:
            if k == choice[0]:
                skip = True
                break
        if not skip:
            self.choices += (choice, )

    def choice_field(self, **kwargs):
        if self.hidden:
            kwargs['widget'] = forms.MultipleHiddenInput()
        from askbot.deps.livesettings.forms import LocalizedChoiceField
        return LocalizedChoiceField(choices=self.choices, **kwargs)

    def _choice_values(self):
        choices = self.choices
        vals = self.value
        return [x for x in choices if x[0] in vals]

    choice_values = property(fget=_choice_values)

    def copy(self):
        new_value = self.__class__(self.group, self.key)
        new_value.__dict__ = self.__dict__.copy()
        return new_value

    def _default_text(self):
        if not self.use_default or force_unicode(self.default) == '':
            note = ""
        elif self.choices:
            work = []
            for x in self.choices:
                if x[0] in self.default:
                    work.append(force_unicode(x[1]))
            note = _('Default value: ') + unicode(u", ".join(work))
        else:
            note = _("Default value: %s") % force_unicode(self.default)

        return note

    default_text = property(fget=_default_text)

    def enabled(self):
        enabled = False
        try:
            if not self.requires:
                enabled = True
            else:
                v = self.requires.value
                if self.requires.choices:
                    enabled = self.requires_value == v or self.requires_value in v
                elif v:
                    enabled = True
        except SettingNotSet:
            pass
        return enabled

    def make_field(self, **kwargs):
        if self.choices:
            if self.hidden:
                kwargs['widget'] = forms.MultipleHiddenInput()
            field = self.choice_field(**kwargs)
        else:
            if self.hidden:
                kwargs['widget'] = forms.HiddenInput()
            field = self.field(**kwargs)

        field.group = self.group
        field.default_text = _('Default value: ') + \
                self.get_default_editor_value(kwargs.get('language_code'))
        return field

    def make_fields(self, **kwargs):
        if self.localized:
            langs_dict = OrderedDict(django_settings.LANGUAGES)
            default_code = django_settings.LANGUAGE_CODE
            default_name = langs_dict[default_code]
            langs_dict[0] = default_code, default_name
            langs = langs_dict.keys()
        else:
            langs = (django_settings.LANGUAGE_CODE,)

        fields = list()
        for lang in langs:
            kwargs['language_code'] = lang
            fields.append(self.make_field(**kwargs))

        #set initial values
        for field in fields:
            lang = field.language_code
            field.initial = self.get_editor_value(lang)

        if self.localized and len(django_settings.LANGUAGES) > 1:
            for field in fields:
                lang_name = unicode(langs_dict[field.language_code])
                field.label += mark_safe(' <span class="lang">(%s)</span>' % lang_name)

        return fields

    def make_setting_with_value(self, value, language_code=None):
        db_value = self.get_db_prep_save(value)
        return self.make_setting(db_value, language_code=language_code)

    def make_setting(self, db_value, language_code=None):
        log.debug('new setting %s.%s', self.group.key, self.key)
        key = self.key
        if self.localized:
            key += '_' + format_setting_name(language_code or get_language())
        return Setting(group=self.group.key, key=key, value=db_value)

    def _setting(self):
        key = self.key
        if self.localized:
            key += '_' + format_setting_name(get_language())
        return find_setting(self.group.key, key)

    #here we have duplicationg with get_setting function
    setting = property(fget = _setting)

    def get_setting(self, language_code=None):
        key = self.key
        if self.localized and language_code:
            key += '_' + format_setting_name(language_code)
        return find_setting(self.group.key, key)

    def _value(self):
        use_db, overrides = get_overrides()

        lang = get_language()

        key = self.key
        if self.localized:
            key += '_' + format_setting_name(lang)

        if not use_db:
            try:
                val = overrides[self.group.key][key]
            except KeyError:
                if self.use_default:
                    val = self.default
                else:
                    raise SettingNotSet('%s.%s is not in your LIVESETTINGS_OPTIONS' % (self.group.key, key))

        else:
            try:
                val = self.setting.value

            except SettingNotSet, sns:

                if self.localized and lang == django_settings.LANGUAGE_CODE:
                    try:
                        unlocalized_setting = find_setting(self.group.key, self.key)
                        return unlocalized_setting.value
                    except SettingNotSet:
                        pass

                if self.use_default:
                    val = self.default
                    if overrides:
                        # maybe override the default
                        grp = overrides.get(self.group.key, {})
                        if grp.has_key(key):
                            val = grp[self.key]
                else:
                    val = NOTSET

            except AttributeError, ae:
                log.error("Attribute error: %s", ae)
                log.error("%s: Could not get _value of %s", key, self.setting)
                raise(ae)

            except Exception, e:
                global _WARN
                log.error(e)
                if str(e).find("configuration_setting") > -1:
                    if not _WARN.has_key('configuration_setting'):
                        log.warn('Error loading setting %s.%s from table, OK if you are in syncdb', self.group.key, key)
                        _WARN['configuration_setting'] = True

                    if self.use_default:
                        val = self.default
                    else:
                        raise ImproperlyConfigured("All settings used in startup must have defaults, %s.%s does not", self.group.key, key)
                else:
                    import traceback
                    traceback.print_exc()
                    log.warn("Problem finding settings %s.%s, %s", self.group.key, key, e)
                    raise SettingNotSet("Startup error, couldn't load %s.%s" %(self.group.key, key))
Exemple #9
0
    def _value(self):
        use_db, overrides = get_overrides()

        lang = get_language()

        key = self.key
        if self.localized:
            key += '_' + format_setting_name(lang)

        if not use_db:
            try:
                val = overrides[self.group.key][key]
            except KeyError:
                if self.use_default:
                    val = self.default
                else:
                    raise SettingNotSet(
                        '%s.%s is not in your LIVESETTINGS_OPTIONS' %
                        (self.group.key, key))

        else:
            try:
                val = self.setting.value

            except SettingNotSet as sns:

                if self.localized and lang == django_settings.LANGUAGE_CODE:
                    try:
                        unlocalized_setting = find_setting(
                            self.group.key, self.key)
                        return unlocalized_setting.value
                    except SettingNotSet:
                        pass

                if self.use_default:
                    val = self.default
                    if overrides:
                        # maybe override the default
                        grp = overrides.get(self.group.key, {})
                        if grp.has_key(key):
                            val = grp[self.key]
                else:
                    val = NOTSET

            except AttributeError as ae:
                log.error("Attribute error: %s", ae)
                log.error("%s: Could not get _value of %s", key, self.setting)
                raise (ae)

            except Exception as e:
                global _WARN
                log.error(e)
                if str(e).find("configuration_setting") > -1:
                    if not _WARN.has_key('configuration_setting'):
                        log.warn(
                            'Error loading setting %s.%s from table, OK if you are in syncdb',
                            self.group.key, key)
                        _WARN['configuration_setting'] = True

                    if self.use_default:
                        val = self.default
                    else:
                        raise ImproperlyConfigured(
                            "All settings used in startup must have defaults, %s.%s does not",
                            self.group.key, key)
                else:
                    import traceback
                    traceback.print_exc()
                    log.warn("Problem finding settings %s.%s, %s",
                             self.group.key, key, e)
                    raise SettingNotSet("Startup error, couldn't load %s.%s" %
                                        (self.group.key, key))
        return val