当前位置: 首页>>代码示例>>Python>>正文


Python registry.Apps类代码示例

本文整理汇总了Python中django.apps.registry.Apps的典型用法代码示例。如果您正苦于以下问题:Python Apps类的具体用法?Python Apps怎么用?Python Apps使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Apps类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: render

 def render(self, include_real=None, ignore_swappable=False, skip_cache=False):
     "Turns the project state into actual models in a new Apps"
     if self.apps is None or skip_cache:
         # Any apps in self.real_apps should have all their models included
         # in the render. We don't use the original model instances as there
         # are some variables that refer to the Apps object.
         # FKs/M2Ms from real apps are also not included as they just
         # mess things up with partial states (due to lack of dependencies)
         real_models = []
         for app_label in self.real_apps:
             app = global_apps.get_app_config(app_label)
             for model in app.get_models():
                 real_models.append(ModelState.from_model(model, exclude_rels=True))
         # Populate the app registry with a stub for each application.
         app_labels = set(model_state.app_label for model_state in self.models.values())
         self.apps = Apps([AppConfigStub(label) for label in sorted(self.real_apps + list(app_labels))])
         # We keep trying to render the models in a loop, ignoring invalid
         # base errors, until the size of the unrendered models doesn't
         # decrease by at least one, meaning there's a base dependency loop/
         # missing base.
         unrendered_models = list(self.models.values()) + real_models
         while unrendered_models:
             new_unrendered_models = []
             for model in unrendered_models:
                 try:
                     model.render(self.apps)
                 except InvalidBasesError:
                     new_unrendered_models.append(model)
             if len(new_unrendered_models) == len(unrendered_models):
                 raise InvalidBasesError(
                     "Cannot resolve bases for %r\nThis can happen if you are inheriting models from an "
                     "app with migrations (e.g. contrib.auth)\n in an app with no migrations; see "
                     "https://docs.djangoproject.com/en/1.7/topics/migrations/#dependencies "
                     "for more" % new_unrendered_models
                 )
             unrendered_models = new_unrendered_models
         # make sure apps has no dangling references
         if self.apps._pending_lookups:
             # There's some lookups left. See if we can first resolve them
             # ourselves - sometimes fields are added after class_prepared is sent
             for lookup_model, operations in self.apps._pending_lookups.items():
                 try:
                     model = self.apps.get_model(lookup_model[0], lookup_model[1])
                 except LookupError:
                     app_label = "%s.%s" % (lookup_model[0], lookup_model[1])
                     if app_label == settings.AUTH_USER_MODEL and ignore_swappable:
                         continue
                     # Raise an error with a best-effort helpful message
                     # (only for the first issue). Error message should look like:
                     # "ValueError: Lookup failed for model referenced by
                     # field migrations.Book.author: migrations.Author"
                     msg = "Lookup failed for model referenced by field {field}: {model[0]}.{model[1]}"
                     raise ValueError(msg.format(field=operations[0][1], model=lookup_model))
                 else:
                     do_pending_lookups(model)
     try:
         return self.apps
     finally:
         if skip_cache:
             self.apps = None
开发者ID:Ethan3600,项目名称:django,代码行数:60,代码来源:state.py

示例2: render

 def render(self):
     "Turns the project state into actual models in a new Apps"
     if self.apps is None:
         self.apps = Apps()
         # Populate the app registry with a stub for each application.
         app_labels = set(model_state.app_label for model_state in self.models.values())
         app_configs = [AppConfigStub(label) for label in sorted(app_labels)]
         self.apps.populate_apps(app_configs)
         self.apps.populate_models()
         # We keep trying to render the models in a loop, ignoring invalid
         # base errors, until the size of the unrendered models doesn't
         # decrease by at least one, meaning there's a base dependency loop/
         # missing base.
         unrendered_models = list(self.models.values())
         while unrendered_models:
             new_unrendered_models = []
             for model in unrendered_models:
                 try:
                     model.render(self.apps)
                 except InvalidBasesError:
                     new_unrendered_models.append(model)
             if len(new_unrendered_models) == len(unrendered_models):
                 raise InvalidBasesError("Cannot resolve bases for %r" % new_unrendered_models)
             unrendered_models = new_unrendered_models
     return self.apps
开发者ID:Chukwunonso,项目名称:django,代码行数:25,代码来源:state.py

示例3: get_models

def get_models():
    result = []
    apps = Apps(settings.INSTALLED_APPS)
    for app_config in apps.get_app_configs():
        try:
            import_module('%s.comments' % app_config.module.__name__)
        except ImportError:
            pass
        except Exception as e:
            raise e

        for attr_name in dir(app_config.models_module):
            attr = getattr(app_config.models_module, attr_name)
            if isinstance(attr, ModelBase) and attr.__module__ == '%s.models' % app_config.module.__name__:
                result.append(attr)
    return result
开发者ID:kelsoncm,项目名称:django-model-documentation,代码行数:16,代码来源:__init__.py

示例4: render

 def render(self, include_real=None):
     "Turns the project state into actual models in a new Apps"
     if self.apps is None:
         # Any apps in self.real_apps should have all their models included
         # in the render. We don't use the original model instances as there
         # are some variables that refer to the Apps object.
         real_models = []
         for app_label in self.real_apps:
             app = global_apps.get_app_config(app_label)
             for model in app.get_models():
                 real_models.append(ModelState.from_model(model))
         # Populate the app registry with a stub for each application.
         app_labels = set(model_state.app_label for model_state in self.models.values())
         self.apps = Apps([AppConfigStub(label) for label in sorted(self.real_apps + list(app_labels))])
         # We keep trying to render the models in a loop, ignoring invalid
         # base errors, until the size of the unrendered models doesn't
         # decrease by at least one, meaning there's a base dependency loop/
         # missing base.
         unrendered_models = list(self.models.values()) + real_models
         while unrendered_models:
             new_unrendered_models = []
             for model in unrendered_models:
                 try:
                     model.render(self.apps)
                 except InvalidBasesError:
                     new_unrendered_models.append(model)
             if len(new_unrendered_models) == len(unrendered_models):
                 raise InvalidBasesError("Cannot resolve bases for %r" % new_unrendered_models)
             unrendered_models = new_unrendered_models
         # make sure apps has no dangling references
         if self.apps._pending_lookups:
             # There's some lookups left. See if we can first resolve them
             # ourselves - sometimes fields are added after class_prepared is sent
             for lookup_model, operations in self.apps._pending_lookups.items():
                 try:
                     model = self.apps.get_model(lookup_model[0], lookup_model[1])
                 except LookupError:
                     # If the lookup failed to something that looks like AUTH_USER_MODEL,
                     # give a better error message about how you can't change it (#22563)
                     extra_message = ""
                     if "%s.%s" % (lookup_model[0], lookup_model[1]) == settings.AUTH_USER_MODEL:
                         extra_message = (
                             "\nThe missing model matches AUTH_USER_MODEL; if you've changed the value of this" +
                             "\nsetting after making a migration, be aware that this is not supported. If you" +
                             "\nchange AUTH_USER_MODEL you must delete and recreate migrations for its app."
                         )
                     # Raise an error with a best-effort helpful message
                     # (only for the first issue). Error message should look like:
                     # "ValueError: Lookup failed for model referenced by
                     # field migrations.Book.author: migrations.Author"
                     raise ValueError("Lookup failed for model referenced by field {field}: {model[0]}.{model[1]}{extra_message}".format(
                         field = operations[0][1],
                         model = lookup_model,
                         extra_message = extra_message,
                     ))
                 else:
                     do_pending_lookups(model)
     return self.apps
开发者ID:hexinH,项目名称:django,代码行数:58,代码来源:state.py

示例5: test_dynamic_load

 def test_dynamic_load(self):
     """
     Makes a new model at runtime and ensures it goes into the right place.
     """
     old_models = apps.get_models(apps.get_app_config("apps").models_module)
     # Construct a new model in a new app registry
     body = {}
     new_apps = Apps()
     meta_contents = {"app_label": "apps", "apps": new_apps}
     meta = type(str("Meta"), tuple(), meta_contents)
     body["Meta"] = meta
     body["__module__"] = TotallyNormal.__module__
     temp_model = type(str("SouthPonies"), (models.Model,), body)
     # Make sure it appeared in the right place!
     self.assertEqual(old_models, apps.get_models(apps.get_app_config("apps").models_module))
     with self.assertRaises(LookupError):
         apps.get_model("apps", "SouthPonies")
     self.assertEqual(new_apps.get_model("apps", "SouthPonies"), temp_model)
开发者ID:Chukwunonso,项目名称:django,代码行数:18,代码来源:tests.py

示例6: test_dynamic_load

 def test_dynamic_load(self):
     """
     Makes a new model at runtime and ensures it goes into the right place.
     """
     old_models = list(apps.get_app_config("apps").get_models())
     # Construct a new model in a new app registry
     body = {}
     new_apps = Apps(["apps"])
     meta_contents = {
         'app_label': "apps",
         'apps': new_apps,
     }
     meta = type("Meta", tuple(), meta_contents)
     body['Meta'] = meta
     body['__module__'] = TotallyNormal.__module__
     temp_model = type("SouthPonies", (models.Model,), body)
     # Make sure it appeared in the right place!
     self.assertEqual(list(apps.get_app_config("apps").get_models()), old_models)
     with self.assertRaises(LookupError):
         apps.get_model("apps", "SouthPonies")
     self.assertEqual(new_apps.get_model("apps", "SouthPonies"), temp_model)
开发者ID:Damgaard,项目名称:django,代码行数:21,代码来源:tests.py

示例7: ProjectState

class ProjectState(object):
    """
    Represents the entire project's overall state.
    This is the item that is passed around - we do it here rather than at the
    app level so that cross-app FKs/etc. resolve properly.
    """

    def __init__(self, models=None, real_apps=None):
        self.models = models or {}
        self.apps = None
        # Apps to include from main registry, usually unmigrated ones
        self.real_apps = real_apps or []

    def add_model_state(self, model_state):
        self.models[(model_state.app_label, model_state.name.lower())] = model_state

    def clone(self):
        "Returns an exact copy of this ProjectState"
        return ProjectState(
            models=dict((k, v.clone()) for k, v in self.models.items()),
            real_apps=self.real_apps,
        )

    def render(self, include_real=None, ignore_swappable=False, skip_cache=False):
        "Turns the project state into actual models in a new Apps"
        if self.apps is None or skip_cache:
            # Any apps in self.real_apps should have all their models included
            # in the render. We don't use the original model instances as there
            # are some variables that refer to the Apps object.
            # FKs/M2Ms from real apps are also not included as they just
            # mess things up with partial states (due to lack of dependencies)
            real_models = []
            for app_label in self.real_apps:
                app = global_apps.get_app_config(app_label)
                for model in app.get_models():
                    real_models.append(ModelState.from_model(model, exclude_rels=True))
            # Populate the app registry with a stub for each application.
            app_labels = set(model_state.app_label for model_state in self.models.values())
            self.apps = Apps([AppConfigStub(label) for label in sorted(self.real_apps + list(app_labels))])
            # We keep trying to render the models in a loop, ignoring invalid
            # base errors, until the size of the unrendered models doesn't
            # decrease by at least one, meaning there's a base dependency loop/
            # missing base.
            unrendered_models = list(self.models.values()) + real_models
            while unrendered_models:
                new_unrendered_models = []
                for model in unrendered_models:
                    try:
                        model.render(self.apps)
                    except InvalidBasesError:
                        new_unrendered_models.append(model)
                if len(new_unrendered_models) == len(unrendered_models):
                    raise InvalidBasesError("Cannot resolve bases for %r\nThis can happen if you are inheriting models from an app with migrations (e.g. contrib.auth)\n in an app with no migrations; see https://docs.djangoproject.com/en/1.7/topics/migrations/#dependencies for more" % new_unrendered_models)
                unrendered_models = new_unrendered_models
            # make sure apps has no dangling references
            if self.apps._pending_lookups:
                # There's some lookups left. See if we can first resolve them
                # ourselves - sometimes fields are added after class_prepared is sent
                for lookup_model, operations in self.apps._pending_lookups.items():
                    try:
                        model = self.apps.get_model(lookup_model[0], lookup_model[1])
                    except LookupError:
                        if "%s.%s" % (lookup_model[0], lookup_model[1]) == settings.AUTH_USER_MODEL and ignore_swappable:
                            continue
                        # Raise an error with a best-effort helpful message
                        # (only for the first issue). Error message should look like:
                        # "ValueError: Lookup failed for model referenced by
                        # field migrations.Book.author: migrations.Author"
                        raise ValueError("Lookup failed for model referenced by field {field}: {model[0]}.{model[1]}".format(
                            field=operations[0][1],
                            model=lookup_model,
                        ))
                    else:
                        do_pending_lookups(model)
        try:
            return self.apps
        finally:
            if skip_cache:
                self.apps = None

    @classmethod
    def from_apps(cls, apps):
        "Takes in an Apps and returns a ProjectState matching it"
        app_models = {}
        for model in apps.get_models(include_swapped=True):
            model_state = ModelState.from_model(model)
            app_models[(model_state.app_label, model_state.name.lower())] = model_state
        return cls(app_models)

    def __eq__(self, other):
        if set(self.models.keys()) != set(other.models.keys()):
            return False
        if set(self.real_apps) != set(other.real_apps):
            return False
        return all(model == other.models[key] for key, model in self.models.items())

    def __ne__(self, other):
        return not (self == other)
开发者ID:Chwen,项目名称:django,代码行数:98,代码来源:state.py

示例8: ProjectState

class ProjectState(object):
    """
    Represents the entire project's overall state.
    This is the item that is passed around - we do it here rather than at the
    app level so that cross-app FKs/etc. resolve properly.
    """

    def __init__(self, models=None, real_apps=None):
        self.models = models or {}
        self.apps = None
        # Apps to include from main registry, usually unmigrated ones
        self.real_apps = real_apps or []

    def add_model_state(self, model_state):
        self.models[(model_state.app_label, model_state.name.lower())] = model_state

    def clone(self):
        "Returns an exact copy of this ProjectState"
        return ProjectState(
            models=dict((k, v.clone()) for k, v in self.models.items()),
            real_apps=self.real_apps,
        )

    def render(self, include_real=None):
        "Turns the project state into actual models in a new Apps"
        if self.apps is None:
            # Any apps in self.real_apps should have all their models included
            # in the render. We don't use the original model instances as there
            # are some variables that refer to the Apps object.
            real_models = []
            for app_label in self.real_apps:
                app = global_apps.get_app_config(app_label)
                for model in app.get_models():
                    real_models.append(ModelState.from_model(model))
            # Populate the app registry with a stub for each application.
            app_labels = set(model_state.app_label for model_state in self.models.values())
            self.apps = Apps([AppConfigStub(label) for label in sorted(self.real_apps + list(app_labels))])
            # We keep trying to render the models in a loop, ignoring invalid
            # base errors, until the size of the unrendered models doesn't
            # decrease by at least one, meaning there's a base dependency loop/
            # missing base.
            unrendered_models = list(self.models.values()) + real_models
            while unrendered_models:
                new_unrendered_models = []
                for model in unrendered_models:
                    try:
                        model.render(self.apps)
                    except InvalidBasesError:
                        new_unrendered_models.append(model)
                if len(new_unrendered_models) == len(unrendered_models):
                    raise InvalidBasesError("Cannot resolve bases for %r" % new_unrendered_models)
                unrendered_models = new_unrendered_models
            # make sure apps has no dangling references
            if self.apps._pending_lookups:
                # There's some lookups left. See if we can first resolve them
                # ourselves - sometimes fields are added after class_prepared is sent
                for lookup_model, operations in self.apps._pending_lookups.items():
                    try:
                        model = self.apps.get_model(lookup_model[0], lookup_model[1])
                    except LookupError:
                        # If the lookup failed to something that looks like AUTH_USER_MODEL,
                        # give a better error message about how you can't change it (#22563)
                        extra_message = ""
                        if "%s.%s" % (lookup_model[0], lookup_model[1]) == settings.AUTH_USER_MODEL:
                            extra_message = (
                                "\nThe missing model matches AUTH_USER_MODEL; if you've changed the value of this" +
                                "\nsetting after making a migration, be aware that this is not supported. If you" +
                                "\nchange AUTH_USER_MODEL you must delete and recreate migrations for its app."
                            )
                        # Raise an error with a best-effort helpful message
                        # (only for the first issue). Error message should look like:
                        # "ValueError: Lookup failed for model referenced by
                        # field migrations.Book.author: migrations.Author"
                        raise ValueError("Lookup failed for model referenced by field {field}: {model[0]}.{model[1]}{extra_message}".format(
                            field = operations[0][1],
                            model = lookup_model,
                            extra_message = extra_message,
                        ))
                    else:
                        do_pending_lookups(model)
        return self.apps

    @classmethod
    def from_apps(cls, apps):
        "Takes in an Apps and returns a ProjectState matching it"
        app_models = {}
        for model in apps.get_models():
            model_state = ModelState.from_model(model)
            app_models[(model_state.app_label, model_state.name.lower())] = model_state
        return cls(app_models)

    def __eq__(self, other):
        if set(self.models.keys()) != set(other.models.keys()):
            return False
        if set(self.real_apps) != set(other.real_apps):
            return False
        return all(model == other.models[key] for key, model in self.models.items())

    def __ne__(self, other):
        return not (self == other)
开发者ID:hexinH,项目名称:django,代码行数:100,代码来源:state.py

示例9: ProjectState

class ProjectState(object):
    """
    Represents the entire project's overall state.
    This is the item that is passed around - we do it here rather than at the
    app level so that cross-app FKs/etc. resolve properly.
    """

    def __init__(self, models=None):
        self.models = models or {}
        self.apps = None

    def add_model_state(self, model_state):
        self.models[(model_state.app_label, model_state.name.lower())] = model_state

    def clone(self):
        "Returns an exact copy of this ProjectState"
        return ProjectState(
            models=dict((k, v.clone()) for k, v in self.models.items())
        )

    def render(self):
        "Turns the project state into actual models in a new Apps"
        if self.apps is None:
            self.apps = Apps()
            # Populate the app registry with a stub for each application.
            app_labels = set(model_state.app_label for model_state in self.models.values())
            app_configs = [AppConfigStub(label) for label in sorted(app_labels)]
            self.apps.populate_apps(app_configs)
            self.apps.populate_models()
            # We keep trying to render the models in a loop, ignoring invalid
            # base errors, until the size of the unrendered models doesn't
            # decrease by at least one, meaning there's a base dependency loop/
            # missing base.
            unrendered_models = list(self.models.values())
            while unrendered_models:
                new_unrendered_models = []
                for model in unrendered_models:
                    try:
                        model.render(self.apps)
                    except InvalidBasesError:
                        new_unrendered_models.append(model)
                if len(new_unrendered_models) == len(unrendered_models):
                    raise InvalidBasesError("Cannot resolve bases for %r" % new_unrendered_models)
                unrendered_models = new_unrendered_models
        return self.apps

    @classmethod
    def from_apps(cls, apps):
        "Takes in an Apps and returns a ProjectState matching it"
        app_models = {}
        for model in apps.get_models():
            model_state = ModelState.from_model(model)
            app_models[(model_state.app_label, model_state.name.lower())] = model_state
        return cls(app_models)

    def __eq__(self, other):
        if set(self.models.keys()) != set(other.models.keys()):
            return False
        return all(model == other.models[key] for key, model in self.models.items())

    def __ne__(self, other):
        return not (self == other)
开发者ID:Chukwunonso,项目名称:django,代码行数:62,代码来源:state.py


注:本文中的django.apps.registry.Apps类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。