コード例 #1
0
    def command_line_config(self):
        """
        settings.py is the basis

        if wants to change them by command line arguments,
        the existing option will be transformed to the value type in settings.py
        the unexisting option will be treated as string by default,
        and transform to certain type if `!<type>` was added after the value.

        example:
        $ python app.py --PORT=1000

        NOTE This method is deprecated, use `torext.script` to parse command line arguments instead.
        """

        args = sys.argv[1:]
        args_dict = {}
        existed_keys = []
        new_keys = []

        for t in args:
            if not t.startswith('--'):
                raise errors.ArgsParseError('Bad arg: %s' % t)
            try:
                key, value = tuple(t[2:].split('='))
            except:
                raise errors.ArgsParseError('Bad arg: %s' % t)

            args_dict[key] = value

            if key in settings:
                existed_keys.append(key)
            else:
                new_keys.append(key)

        if existed_keys:
            app_log.debug('Changed settings:')
            for i in existed_keys:
                before = settings[i]
                type_ = type(before)
                if type_ is bool:
                    if args_dict[i] == 'True':
                        _value = True
                    elif args_dict[i] == 'False':
                        _value = False
                    else:
                        raise errors.ArgsParseError('%s should only be True or False' % i)
                else:
                    _value = type_(args_dict[i])
                settings[i] = _value
                app_log.debug('  %s  [%s]%s (%s)', i, type(settings[i]), settings[i], before)

        if new_keys:
            app_log.debug('New settings:')
            for i in new_keys:
                settings[i] = args_dict[i]
                app_log.debug('  %s  %s', i, args_dict[i])

        # NOTE if ``command_line_config`` is called, logging must be re-configed
        self.update_settings({})
コード例 #2
0
def _convert_type(raw, before):
    type_ = type(before)
    if type_ is bool:
        if raw == 'True':
            value = True
        elif raw == 'False':
            value = False
        else:
            raise errors.ArgsParseError('Should only be True or False, got: %s' % raw)
    else:
        value = type_(raw)
    return value