Example #1
0
def register_app(app_label, app):
    """Register a new app in the registry.

    This must be balanced with a :py:func:`unregister_app` call.

    Args:
        app_label (str):
            The label of the app.

        app (module):
            The app module.
    """
    if apps:
        # Django >= 1.7
        app_config = AppConfig(app.__name__, app)
        app_config.label = app_label
        app_config.models_module = app

        apps.set_installed_apps(settings.INSTALLED_APPS + [app_config])
    else:
        # Django < 1.7
        cache.app_store[app] = len(cache.app_store)

        if hasattr(cache, 'app_labels'):
            cache.app_labels[app_label] = app
Example #2
0
    def handle(self, *app_labels, **options):
        try:
            if app_labels and len(app_labels) > 0:
                app_configs = [
                    apps.get_app_config(app_label) for app_label in app_labels
                ]
            else:
                app_configs = [
                    AppConfig.create(app_label)
                    for app_label in settings.INSTALLED_APPS
                ]
        except (LookupError, ImportError) as e:
            raise CommandError(
                "%s. Are you sure your INSTALLED_APPS setting is correct?" % e)

        for app_config in app_configs:
            try:
                call_command('migrate', app_config.name.split('.')[-1], 'zero')
            except CommandError:
                continue

        call_command('migrate')

        if options['seed'] is not None:
            if len(options['seed']) == 0:
                call_command('seed')
            else:
                call_command('seed', *options['seed'])
def do_all_content(parser, token):
    """
    Returns all entries for a particular model.

    Example usage:

    {% load fetch_content %}
    {% get_all_content application_name.model_name as foo %}
    {% for bar in foo %}
        {{ bar.attribute }}
    {% endfor %}
    """
    bits = token.split_contents()
    if len(bits) != 4:
        raise template.TemplateSyntaxError("'get_all_content' takes exactly "
                                           "three arguments")
    model_args = bits[1].split('.')
    if len(model_args) != 2:
        raise template.TemplateSyntaxError("First argument to "
                                           "'get_all_content' must be an "
                                           "'application name'.'model name' "
                                           "string")
    try:
        # < Django 1.9
        model = get_model(*model_args)
    except:
        # Django 1.9
        model = AppConfig.get_model(*model_args)
    if model is None:
        raise template.TemplateSyntaxError("'get_all_content' tag got an "
                                           "invalid model: %s" % bits[1])
    return AllContentNode(model, bits[3])
def do_latest_content(parser, token):
    """
    Returns a specific number of entries for a particular model.
    (If the model is sorted by date published they will be sorted that way
        hence the name get_latest_content.)

    Example usage:

    {% load fetch_content %}
    {% get_latest_content application_name.model_name 5 as foo %}
    {% for bar in foo %}
        {{ bar.attribute }}
    {% endfor %}
    """
    bits = token.split_contents()
    if len(bits) != 5:
        raise template.TemplateSyntaxError("'get_latest_content' takes "
                                           "exactly four arguments")
    model_args = bits[1].split('.')
    if len(model_args) != 2:
        raise template.TemplateSyntaxError("First argument to "
                                           "'get_latest_content' must be an "
                                           "'application name'.'model name' "
                                           "string")
    try:
        # < Django 1.9
        model = get_model(*model_args)
    except:
        # Django 1.9
        model = AppConfig.get_model(*model_args)
    if model is None:
        raise template.TemplateSyntaxError("'get_latest_content' tag got an "
                                           "invalid model: %s" % bits[1])
    return LatestContentNode(model, bits[2], bits[4])
Example #5
0
 def _load_all_socket_listeners(self):
     for app in settings.INSTALLED_APPS:
         app_config = AppConfig.create(app)
         try:
             from app_config.module import sockets
         except ImportError:
             pass
Example #6
0
def setup():
    DB_FILE = NAME + '.db'
    with open(DB_FILE, 'w'):
        pass  # wipe the database
    settings.configure(DEBUG=True,
                       DATABASES={
                           DEFAULT_DB_ALIAS: {
                               'ENGINE': 'django.db.backends.sqlite3',
                               'NAME': DB_FILE
                           }
                       },
                       LOGGING={
                           'version': 1,
                           'disable_existing_loggers': False,
                           'formatters': {
                               'debug': {
                                   'format': '%(asctime)s[%(levelname)s]'
                                   '%(name)s.%(funcName)s(): %(message)s',
                                   'datefmt': '%Y-%m-%d %H:%M:%S'
                               }
                           },
                           'handlers': {
                               'console': {
                                   'level': 'DEBUG',
                                   'class': 'logging.StreamHandler',
                                   'formatter': 'debug'
                               }
                           },
                           'root': {
                               'handlers': ['console'],
                               'level': 'WARN'
                           },
                           'loggers': {
                               "django.db": {
                                   "level": "WARN"
                               }
                           }
                       })
    app_config = AppConfig(NAME, sys.modules['__main__'])
    apps.populate([app_config])
    django.setup()
    original_new_func = ModelBase.__new__

    @staticmethod
    def patched_new(cls, name, bases, attrs):
        if 'Meta' not in attrs:

            class Meta:
                app_label = NAME

            attrs['Meta'] = Meta
        return original_new_func(cls, name, bases, attrs)

    ModelBase.__new__ = patched_new
Example #7
0
def _repopulate_apps(apps):
    """
    After the initial loading of the settings, some djangoapps can override the AppConfig.ready() method
    to alter the settings in a particular way.
    In this case we need to run the app config again.
    We delegate the decision to the specific tenant on the EDNX_TENANT_INSTALLED_APPS key.
    If present, the key is passed in the apps argument
    """
    LOG.debug("PID: %s REPOPULATING APPS | %s", os.getpid(), apps)
    for entry in apps:
        app_config = AppConfig.create(entry)
        app_config.ready()
Example #8
0
    def _populate_apps(self, apps_list):
        """
        A function to more efficiently manipulate django app list.
        """
        apps = self._apps

        missing = set(self.installed_apps) - set(apps_list)
        new = set(apps_list) - set(self.installed_apps)

        apps.apps_ready = apps.models_ready = apps.ready = False

        with apps._lock:

            for entry in apps_list + list(self.installed_apps):

                if isinstance(entry, AppConfig):
                    app_config = entry
                else:
                    app_config = AppConfig.create(entry)

                label = app_config.label

                if entry in missing and label in apps.app_configs:
                    del apps.app_configs[label]
                elif entry in new and label not in apps.app_configs:
                    apps.app_configs[label] = app_config
                    app_config.apps = apps

            counts = Counter(app_config.name
                             for app_config in apps.app_configs.values())
            duplicates = [
                name for name, count in counts.most_common() if count > 1
            ]
            if duplicates:
                raise ImproperlyConfigured("Application names aren't unique, "
                                           "duplicates: %s" %
                                           ", ".join(duplicates))

            apps.apps_ready = True

            for app_config in apps.app_configs.values():
                app_config.import_models()

            apps.clear_cache()

            apps.models_ready = True

            for app_config in apps.get_app_configs():
                if app_config.name in new:
                    app_config.ready()

            apps.ready = True
Example #9
0
def register_app(app_label, app):
    """Register a new app in the registry.

    This must be balanced with a :py:func:`unregister_app` call.

    Args:
        app_label (str):
            The label of the app.

        app (module):
            The app module.
    """
    if apps:
        # Django >= 1.7
        app_config = AppConfig(app.__name__, app)
        app_config.label = app_label

        apps.set_installed_apps(settings.INSTALLED_APPS + [app_config])
    else:
        # Django < 1.7
        cache.app_store[app] = len(cache.app_store)

        if hasattr(cache, 'app_labels'):
            cache.app_labels[app_label] = app
Example #10
0
 def tuck_up_pants(mcs, kls):
     """
     implicit initialization of django models registry.
     :param kls:
     :return:
     """
     label = kls._meta.app_label
     app_name = "noc.%s" % label
     # Fake up apps.populate
     app_config = apps.app_configs.get(label)
     if not app_config:
         app_config = AppConfig.create(app_name)
         app_config.apps = apps  # Hipsters have many pants now. Tuck up default pants
         app_config.models = {}
         apps.app_configs[label] = app_config
     # Fake app AppConfig.import_models
     app_config.models = apps.all_models[label]
     # Tests should check all models has tucked pants
     kls._tucked_pants = True
     return kls
def get_app_template_dir(app_name):
    """
    Get the template directory for an application

    We do not use django.db.models.get_app, because this will fail if an
    app does not have any models.

    Returns a full path, or None if the app was not found.
    """
    if app_name in _cache:
        return _cache[app_name]
    template_dir = None
    for app in settings.INSTALLED_APPS:
        app_config = AppConfig.create(app)
        if app_config.name == app_name:
            template_dir = join(abspath(dirname(app_config.module.__file__)),
                                'templates')
            break
    _cache[app_name] = template_dir
    return template_dir
Example #12
0
    def handle(self, *app_labels, **options):
        try:
            if app_labels and len(app_labels) > 0:
                app_configs = [
                    apps.get_app_config(app_label) for app_label in app_labels
                ]
            else:
                app_configs = [
                    AppConfig.create(app_label)
                    for app_label in settings.INSTALLED_APPS
                ]
        except (LookupError, ImportError) as e:
            raise CommandError(
                "%s. Are you sure your INSTALLED_APPS setting is correct?" % e)

        seeders = []
        for app_config in app_configs:
            try:
                module_seeders = import_module('%s.%s' %
                                               (app_config.name, 'seeders'))
            except ImportError:
                continue

            if callable(getattr(module_seeders, 'handle', None)):
                seeders.append({
                    'order': getattr(module_seeders, 'order', 0),
                    'handle': module_seeders.handle
                })
            else:
                raise AttributeError(
                    "You should define 'handle' method in %s." %
                    (app_config.name + '.seeders'))

        seeders = pydash.sort(seeders, key=lambda item: item['order'])

        for seeder in seeders:
            seeder['handle'](self)

        self.stdout.write(
            self.style.SUCCESS('Database seeding completed successfully.'))
ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'axes',
]

MIGRATION_MODULES = {
    AppConfig.create(entry).label: None
    for entry in INSTALLED_APPS
}

AUTHENTICATION_BACKENDS = [
    # AxesBackend should be the first backend in the AUTHENTICATION_BACKENDS list.
    'axes.backends.AxesBackend',

    # Django ModelBackend is the default authentication backend.
    'django.contrib.auth.backends.ModelBackend',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
Example #14
0
from django.apps.config import AppConfig
from django.apps import apps
from django.conf import settings
from django.db.models import signals, Model
from django.db.models.fields import (AutoField, BigIntegerField, DecimalField,
                                     BooleanField)
from .tracking import patch_tracking
from .transaction import patch_transaction
from .fetching import patch_fetching
from .safety import patch_safety

from . import FORBIDDEN_FIELDS, MAX, PK, OK, CU, DU, VF, VU


seen_models = set()
installed_app_labels = [AppConfig.create(entry).label
                        for entry in settings.INSTALLED_APPS]


def get_migration_app():
    """
    If you use timetravel this key must be set in settings.
    The app specified here must be present in INSTALLED_APPS.
    """
    tt_app = getattr(settings, 'TIMETRAVEL_MIGRATION_APP', None)
    if not tt_app:
        raise Exception('No migration app given')
    return tt_app


def process_models(sender, **kwargs):
Example #15
0
 def setUp(self):
     super().setUp()
     # re-run ready as we've changed the settings
     AppConfig.create("kitsune.sumo").ready()
     activate("xx")