def update_or_create_region(region_dict):
        if kwargs.get('limit_to_classes') and Region not in kwargs['limit_to_classes']:
            if Region.objects.filter(key=region_dict['key']).count() != 1:
                raise Exception("Trying to get Region %s, which hasn't been created" % region_dict['key'])
            region_tuple = Region.objects.get(key=region_dict['key']), False, False
        else:
            region_tuple = Region.objects.update_or_create(
                key=region_dict['key'],
                defaults=merge(
                    dict(
                        behavior=get_behavior('default_config_entity'),
                    ),
                    remove_keys(region_dict, ['key', 'media']),
                    dict(
                        creator=User.objects.get(username=UserGroupKey.SUPERADMIN),
                        parent_config_entity=global_config_singleton() if \
                            region_dict['key'] == settings.CLIENT else \
                            update_or_create_region(dict(key=settings.CLIENT, name=settings.CLIENT_NAME))[0]
            )))

        logger.info("{update_or_create} Region {config_entity}".format(update_or_create='Created' if region_tuple[1] else 'Updated', config_entity=region_tuple[0]))


        media = map(lambda medium_config:
                    Medium.objects.update_or_create(
                        key=medium_config.key,
                        defaults=remove_keys(medium_config.__dict__['kwargs'], 'key'))[0],
                    region_dict.get('media', []))

        existing_media = region_tuple[0].media.filter(id__in=map(lambda medium: medium.id, media))
        media_to_add = set(media) - set(existing_media)
        if len(media_to_add) > 0:
            region_tuple[0].media.add(*media_to_add)
        return region_tuple
Ejemplo n.º 2
0
 def __init__(self, *args, **kwargs):
     # Remove any kwargs specific to this class before calling super
     new_kwargs = merge(
         remove_keys(kwargs, ["config_entities", "parent_config_entity"]),
         {"parent_config_entity": kwargs.get("parent_config_entity", global_config_singleton())},
     )
     super(CombinedConfigEntity, self).__init__(*args, **new_kwargs)
     # Set the parent_config_entity, which will function as the parent, if needed. Also reference the config
     # entities whose combined data will makeup this instances ConfigEntity properties
     if kwargs["parent_config_entity"]:
         self.config_entities = kwargs["parent_config_entity"].children()
     elif "config_entities" in kwargs:
         # Just default to the GlobalConfig singleton. This could be smarter and traverse up all the config_entity
         # parents to find the common one.
         self.config_entities = kwargs["config_entities"]
Ejemplo n.º 3
0
 def __init__(self, *args, **kwargs):
     # Remove any kwargs specific to this class before calling super
     new_kwargs = merge(
         remove_keys(
             kwargs,
             ['config_entities', 'parent_config_entity']),
         {'parent_config_entity': kwargs.get('parent_config_entity', global_config_singleton())})
     super(CombinedConfigEntity, self).__init__(*args, **new_kwargs)
     # Set the parent_config_entity, which will function as the parent, if needed. Also reference the config
     # entities whose combined data will makeup this instances ConfigEntity properties
     if kwargs['parent_config_entity']:
         self.config_entities = kwargs['parent_config_entity'].children()
     elif 'config_entities' in kwargs:
         # Just default to the GlobalConfig singleton. This could be smarter and traverse up all the config_entity
         # parents to find the common one.
         self.config_entities = kwargs['config_entities']
Ejemplo n.º 4
0
def on_user_post_save(sender, **kwargs):
    user = kwargs['instance']
    groups = user.groups.all()
    if not groups:
        raise Exception('User %s is not in any groups', user)

    config_entities = set()
    for group in groups:
        config_entity = group.group_hierarchy.config_entity
        if not config_entity and group.name in UserGroupKey.GLOBAL:
            # Each of the GLOBAL groups are a special case--both a global Group and a ConfigEntity Group
            # It purposely doesn't resolve its config_entity but we need it here
            config_entity = global_config_singleton()

        if config_entity:
            config_entities.add(config_entity)

    # We should always have at least one ConfigEntity
    if not config_entities:
        raise Exception('No config entity for user {user}'.format(user=user))

    starting_signal_path = resolvable_module_attr_path(__name__, 'post_save_user_initial')

    scenarios = set()
    for config_entity in config_entities:
        scenarios |= set(config_entity.descendants_by_type(Scenario))

    # randoming order b/c we've had problems with
    # post-save processing of admin-level users causing
    # the machine to run out of available memory, which
    # prevented scenarios later in the list from being processed.
    scenarios = list(scenarios)
    random.shuffle(scenarios)

    for scenario in scenarios:
        post_save_publishing(
            starting_signal_path,
            scenario,
            user,
            instance=user,
            instance_class=User,
            instance_key=user.username,
            signal_proportion_lookup=signal_proportion_lookup,
            dependent_signal_paths=dependent_signal_paths,
            signal_prefix='post_save_user',
            scenario=scenario
        )
Ejemplo n.º 5
0
def on_user_post_save(sender, **kwargs):
    user = kwargs['instance']
    groups = user.groups.all()
    if not groups:
        raise Exception('User %s is not in any groups', user)

    config_entities = set()
    for group in groups:
        config_entity = group.group_hierarchy.config_entity
        if not config_entity and group.name in UserGroupKey.GLOBAL:
            # Each of the GLOBAL groups are a special case--both a global Group and a ConfigEntity Group
            # It purposely doesn't resolve its config_entity but we need it here
            config_entity = global_config_singleton()

        if config_entity:
            config_entities.add(config_entity)

    # We should always have at least one ConfigEntity
    if not config_entities:
        raise Exception('No config entity for user {user}'.format(user=user))

    starting_signal_path = resolvable_module_attr_path(
        __name__, 'post_save_user_initial')

    scenarios = set()
    for config_entity in config_entities:
        scenarios |= set(config_entity.descendants_by_type(Scenario))

    # randoming order b/c we've had problems with
    # post-save processing of admin-level users causing
    # the machine to run out of available memory, which
    # prevented scenarios later in the list from being processed.
    scenarios = list(scenarios)
    random.shuffle(scenarios)

    for scenario in scenarios:
        post_save_publishing(starting_signal_path,
                             scenario,
                             user,
                             instance=user,
                             instance_class=User,
                             instance_key=user.username,
                             signal_proportion_lookup=signal_proportion_lookup,
                             dependent_signal_paths=dependent_signal_paths,
                             signal_prefix='post_save_user',
                             scenario=scenario)
Ejemplo n.º 6
0
def filter_config_entities(**options):
    """
        Filter by 'limit_to_classes' ConfigEntity subclasses and by config_etnity_keys options
    :param options:
    :return:
    """

    global _CACHED_CONFIG_ENTITIES
    if not _CACHED_CONFIG_ENTITIES:
        old_debug = settings.DEBUG
        settings.DEBUG = True
        reset_queries()

        _cached_config_entities = ConfigEntity.objects.filter(deleted=False)

        # This assertion makes sure we aren't overly aggressive in
        # loading the initial ConfigEntity list. In a pinch, comment
        # this out.
        # TODO: Move this to a test.
        total_entities = len(_cached_config_entities)
        assert len(connection.queries) < total_entities*13, (
            "Got %d queries for %d config_entities " % (len(connection.queries), len(_cached_config_entities)))
        settings.DEBUG = old_debug

    # Make sure we only select ConfigEntities related to the current client
    client_region = Region.objects.get(key=settings.CLIENT)
    eligible_ids = map(lambda config_entity: config_entity.id,
                       [global_config_singleton(), client_region] + list(client_region.descendants()))
    config_entities = _cached_config_entities.filter(
        id__in=eligible_ids,
        **compact_kwargs(key__in=options.get('config_entity_keys'))
    )
    # config_entities = ConfigEntity.objects.filter(deleted=False).filter(
    #     **compact_kwargs(key__in=options.get('config_entity_keys')))
    result = sort_config_entities(
        filter(
            lambda config_entity: not options.get('limit_to_classes') or isinstance(config_entity, tuple(options.get('limit_to_classes'))),
            map(lambda config_entity: config_entity.subclassed, config_entities)
        )
    )

    return result
Ejemplo n.º 7
0
    def update_or_create_region(region_dict):
        if kwargs.get('limit_to_classes'
                      ) and Region not in kwargs['limit_to_classes']:
            if Region.objects.filter(key=region_dict['key']).count() != 1:
                raise Exception(
                    "Trying to get Region %s, which hasn't been created" %
                    region_dict['key'])
            region_tuple = Region.objects.get(
                key=region_dict['key']), False, False
        else:
            region_tuple = Region.objects.update_or_create(
                key=region_dict['key'],
                defaults=merge(
                    dict(
                        behavior=get_behavior('default_config_entity'),
                    ),
                    remove_keys(region_dict, ['key', 'media']),
                    dict(
                        creator=User.objects.get(username=UserGroupKey.SUPERADMIN),
                        parent_config_entity=global_config_singleton() if \
                            region_dict['key'] == settings.CLIENT else \
                            update_or_create_region(dict(key=settings.CLIENT, name=settings.CLIENT_NAME))[0]
            )))

        logger.info("{update_or_create} Region {config_entity}".format(
            update_or_create='Created' if region_tuple[1] else 'Updated',
            config_entity=region_tuple[0]))

        media = map(
            lambda medium_config: Medium.objects.
            update_or_create(key=medium_config.key,
                             defaults=remove_keys(
                                 medium_config.__dict__['kwargs'], 'key'))[0],
            region_dict.get('media', []))

        existing_media = region_tuple[0].media.filter(
            id__in=map(lambda medium: medium.id, media))
        media_to_add = set(media) - set(existing_media)
        if len(media_to_add) > 0:
            region_tuple[0].media.add(*media_to_add)
        return region_tuple