コード例 #1
0
ファイル: functions.py プロジェクト: ToeKnee/jelly-roll
        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))
コード例 #2
0
ファイル: functions.py プロジェクト: ToeKnee/jelly-roll
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:
            if not skip_missing:
                raise SettingNotSet("No config %s.%s" % (g, key))

    if unique:
        out = []
        for x in ret:
            if x not in out:
                out.append(x)
        ret = out

    return ret
コード例 #3
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))
コード例 #4
0
ファイル: functions.py プロジェクト: ToeKnee/jelly-roll
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
コード例 #5
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`.
        """
        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.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 'default' in kwargs:
            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(force_text(x[1]))
                note = ugettext('Default value: ') + u", ".join(work)

            else:
                note = _("Default value: %s") % force_text(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):
        try:
            val = self.setting.value

        except SettingNotSet:
            if self.use_default:
                val = self.default
            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 'configuration_setting' not in _WARN:
                    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))