Exemplo n.º 1
0
def get_app_submodule(app_name, module_name):
    '''获取 app settings 模块
    '''
    app_module = import_module(app_name)
    try:
        submodule = import_module('{0}.{1}'.format(app_name, module_name))
    except ImportError:
        if not module_has_submodule(app_module, module_name):
            return None

        else:
            raise

    return submodule
Exemplo n.º 2
0
def load_commands():
    global COMMANDS

    if len(COMMANDS) == 0:
        for f in os.listdir(os.path.join(CURDIR, 'commands')):
            if not f.endswith('.py'):
                continue

            m = import_module('eva.management.commands.{0}'.format(f[:-3]))
            if not hasattr(m, 'Command'):
                logging.warn('%s is not a Command Module!',
                             os.path.join(CURDIR, f))
                continue

            c = m.Command()

            if not (hasattr(c, 'cmd') and hasattr(c, 'help')
                    and hasattr(c, 'run')):
                logging.warn('%s is not a Command Module!',
                             os.path.join(CURDIR, f))
                continue

            COMMANDS[c.cmd] = c

    return COMMANDS
Exemplo n.º 3
0
    def _fetch(lang, fallback=None):

        global _translations

        res = _translations.get(lang, None)
        if res is not None:
            return res

        loc = to_locale(lang)

        def _translation(path):
            try:
                t = gettext_module.translation('eva', path, [loc], DjangoTranslation)
                t.set_language(lang)
                return t
            except IOError:
                return None

        res = _translation(globalpath)

        # We want to ensure that, for example,  "en-gb" and "en-us" don't share
        # the same translation object (thus, merging en-us with a local update
        # doesn't affect en-gb), even though they will both use the core "en"
        # translation. So we have to subvert Python's internal gettext caching.
        base_lang = lambda x: x.split('-', 1)[0]
        if base_lang(lang) in [base_lang(trans) for trans in list(_translations)]:
            res._info = res._info.copy()
            res._catalog = res._catalog.copy()

        def _merge(path):
            t = _translation(path)
            if t is not None:
                if res is None:
                    return t
                else:
                    res.merge(t)
            return res

        for appname in reversed(settings.INSTALLED_APPS):
            app = import_module(appname)
            apppath = os.path.join(os.path.dirname(upath(app.__file__)), 'locale')

            if os.path.isdir(apppath):
                res = _merge(apppath)

        for localepath in reversed(settings.LOCALE_PATHS):
            if os.path.isdir(localepath):
                res = _merge(localepath)

        if res is None:
            if fallback is not None:
                res = fallback
            else:
                return gettext_module.NullTranslations()
        _translations[lang] = res
        return res
Exemplo n.º 4
0
    def __init__(self, settings_module):
        # update this dict from global settings (but only for ALL_CAPS settings)
        for setting in dir(global_settings):
            if setting == setting.upper():
                setattr(self, setting, getattr(global_settings, setting))

        # store the settings module in case someone later cares
        self.SETTINGS_MODULE = settings_module

        try:
            mod = importlib.import_module(self.SETTINGS_MODULE)
        except ImportError as e:
            raise ImportError(
                "Could not import settings '%s' (Is it on sys.path? Is there an import error in the settings file?): %s"
                % (self.SETTINGS_MODULE, e)
            )

        # Settings that should be converted into tuples if they're mistakenly entered
        # as strings.
        tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")

        for setting in dir(mod):
            if setting == setting.upper():
                setting_value = getattr(mod, setting)
                if setting in tuple_settings and \
                        isinstance(setting_value, six.string_types):
                    warnings.warn("The %s setting must be a tuple. Please fix your "
                                  "settings, as auto-correction is now deprecated." % setting,
                                  DeprecationWarning, stacklevel=2)
                    setting_value = (setting_value,) # In case the user forgot the comma.
                setattr(self, setting, setting_value)

        if not self.SECRET_KEY:
            raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")

        if hasattr(time, 'tzset') and self.TIME_ZONE:
            # When we can, attempt to validate the timezone. If we can't find
            # this file, no check happens and it's harmless.
            zoneinfo_root = '/usr/share/zoneinfo'
            if (os.path.exists(zoneinfo_root) and not
                    os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
                raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
            # Move the time zone info into os.environ. See ticket #2315 for why
            # we don't do this unconditionally (breaks Windows).
            os.environ['TZ'] = self.TIME_ZONE
            time.tzset()
Exemplo n.º 5
0
def _load_tests(subdir):
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()

    # 加载 models 测试
    for app in settings.INSTALLED_APPS:

        p = get_app_abspath(app)
        logging.debug('APP(%s:%s)', app, p)

        mp = os.path.join(p, subdir)

        if not os.path.isdir(mp):
            logging.debug('%s: no %s, PASS', app, subdir)
            continue

        for t in _find_tests(mp):
            m = import_module('.'.join([app, subdir.replace('/', '.'), t]))
            s = loader.loadTestsFromModule(m)
            suite.addTests(s)

    return suite
Exemplo n.º 6
0
def _load_tests(subdir):
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()

    # 加载 models 测试
    for app in settings.INSTALLED_APPS:

        p = get_app_abspath(app)
        logging.debug('APP(%s:%s)', app, p)

        mp = os.path.join(p, subdir)

        if not os.path.isdir(mp):
            logging.debug('%s: no %s, PASS', app, subdir)
            continue

        for t in _find_tests(mp):
            m = import_module('.'.join([app, subdir.replace('/', '.'), t]))
            s = loader.loadTestsFromModule(m)
            suite.addTests(s)

    return suite
Exemplo n.º 7
0
def import_by_path(dotted_path, error_prefix=''):
    """
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImproperlyConfigured if something goes wrong.
    """
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        raise ImproperlyConfigured("%s%s doesn't look like a module path" % (
            error_prefix, dotted_path))
    try:
        module = import_module(module_path)
    except ImportError as e:
        msg = '%sError importing module %s: "%s"' % (
            error_prefix, module_path, e)
        six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg),
                    sys.exc_info()[2])
    try:
        attr = getattr(module, class_name)
    except AttributeError:
        raise ImproperlyConfigured('%sModule "%s" does not define a "%s" attribute/class' % (
            error_prefix, module_path, class_name))
    return attr
Exemplo n.º 8
0
def load_commands():
    global COMMANDS

    if len(COMMANDS) == 0:
        for f in os.listdir(os.path.join(CURDIR, 'commands')):
            if not f.endswith('.py'):
                continue

            m = import_module('eva.management.commands.{0}'.format(f[:-3]))
            if not hasattr(m, 'Command'):
                logging.warn('%s is not a Command Module!', os.path.join(CURDIR, f))
                continue

            c = m.Command()

            if not (hasattr(c, 'cmd') and
                    hasattr(c, 'help') and
                    hasattr(c, 'run')):
                logging.warn('%s is not a Command Module!', os.path.join(CURDIR, f))
                continue

            COMMANDS[c.cmd] = c

    return COMMANDS
Exemplo n.º 9
0
def get_app_abspath(app_name):
    '''获取 app 的绝对路径
    '''
    app_module = import_module(app_name)
    return os.path.dirname(os.path.realpath( app_module.__file__ ))