Python django.utils.datastructures.SortedDict() Examples

The following are 30 code examples of django.utils.datastructures.SortedDict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.datastructures , or try the search function .
Example #1
Source File: views.py    From avos with Apache License 2.0 6 votes vote down vote up
def _get_profiles(request, type_p):
    try:
        profiles = api.neutron.profile_list(request, type_p)
    except Exception:
        profiles = []
        msg = _('Network Profiles could not be retrieved.')
        exceptions.handle(request, msg)
    if profiles:
        # Set project name
        tenant_dict = _get_tenant_list(request)
        bindings = api.neutron.profile_bindings_list(request, type_p)
        bindings_dict = datastructures.SortedDict(
            [(b.profile_id, b.tenant_id) for b in bindings])
        for p in profiles:
            project_id = bindings_dict.get(p.id)
            project = tenant_dict.get(project_id)
            p.project_name = getattr(project, 'name', None)
    return profiles 
Example #2
Source File: query.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def bump_prefix(self, exceptions=()):
        """
        Changes the alias prefix to the next letter in the alphabet and
        relabels all the aliases. Even tables that previously had no alias will
        get an alias after this call (it's mostly used for nested queries and
        the outer query will already be using the non-aliased table name).

        Subclasses who create their own prefix should override this method to
        produce a similar result (a new prefix and relabelled aliases).

        The 'exceptions' parameter is a container that holds alias names which
        should not be changed.
        """
        current = ord(self.alias_prefix)
        assert current < ord('Z')
        prefix = chr(current + 1)
        self.alias_prefix = prefix
        change_map = SortedDict()
        for pos, alias in enumerate(self.tables):
            if alias in exceptions:
                continue
            new_alias = '%s%d' % (prefix, pos)
            change_map[alias] = new_alias
            self.tables[pos] = new_alias
        self.change_aliases(change_map) 
Example #3
Source File: options.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def _fill_related_objects_cache(self):
        cache = SortedDict()
        parent_list = self.get_parent_list()
        for parent in self.parents:
            for obj, model in parent._meta.get_all_related_objects_with_model(include_hidden=True):
                if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list:
                    continue
                if not model:
                    cache[obj] = parent
                else:
                    cache[obj] = model
        # Collect also objects which are in relation to some proxy child/parent of self.
        proxy_cache = cache.copy()
        for klass in get_models(include_auto_created=True, only_installed=False):
            if not klass._meta.swapped:
                for f in klass._meta.local_fields:
                    if f.rel and not isinstance(f.rel.to, six.string_types):
                        if self == f.rel.to._meta:
                            cache[RelatedObject(f.rel.to, klass, f)] = None
                            proxy_cache[RelatedObject(f.rel.to, klass, f)] = None
                        elif self.concrete_model == f.rel.to._meta.concrete_model:
                            proxy_cache[RelatedObject(f.rel.to, klass, f)] = None
        self._related_objects_cache = cache
        self._related_objects_proxy_cache = proxy_cache 
Example #4
Source File: base.py    From avos with Apache License 2.0 6 votes vote down vote up
def __init__(self, request, data=None, needs_form_wrapper=None, **kwargs):
        self.request = request
        self.data = data
        self.kwargs = kwargs
        self._needs_form_wrapper = needs_form_wrapper
        self._no_data_message = self._meta.no_data_message
        self.breadcrumb = None
        self.current_item_id = None
        self.permissions = self._meta.permissions

        # Create a new set
        columns = []
        for key, _column in self._columns.items():
            column = copy.copy(_column)
            column.table = self
            columns.append((key, column))
        self.columns = SortedDict(columns)
        self._populate_data_cache()

        # Associate these actions with this table
        for action in self.base_actions.values():
            action.associate_with_table(self)

        self.needs_summary_row = any([col.summation
                                      for col in self.columns.values()]) 
Example #5
Source File: loading.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def register_models(self, app_label, *models):
        """
        Register a set of models as belonging to an app.
        """
        for model in models:
            # Store as 'name: model' pair in a dictionary
            # in the app_models dictionary
            model_name = model._meta.object_name.lower()
            model_dict = self.app_models.setdefault(app_label, SortedDict())
            if model_name in model_dict:
                # The same model may be imported via different paths (e.g.
                # appname.models and project.appname.models). We use the source
                # filename as a means to detect identity.
                fname1 = os.path.abspath(upath(sys.modules[model.__module__].__file__))
                fname2 = os.path.abspath(upath(sys.modules[model_dict[model_name].__module__].__file__))
                # Since the filename extension could be .py the first time and
                # .pyc or .pyo the second time, ignore the extension when
                # comparing.
                if os.path.splitext(fname1)[0] == os.path.splitext(fname2)[0]:
                    continue
            model_dict[model_name] = model
        self._get_models_cache.clear() 
Example #6
Source File: serializers.py    From drf-haystack with MIT License 6 votes vote down vote up
def get_fields(self):
        """
        This returns a dictionary containing the top most fields,
        ``dates``, ``fields`` and ``queries``.
        """
        field_mapping = OrderedDict()
        for field, data in self.instance.items():
            field_mapping.update(
                {field: self.facet_dict_field_class(
                    child=self.facet_list_field_class(child=self.facet_field_serializer_class(data)), required=False)}
            )

        if self.serialize_objects is True:
            field_mapping["objects"] = serializers.SerializerMethodField()

        return field_mapping 
Example #7
Source File: serializers.py    From djangorest-alchemy with MIT License 6 votes vote down vote up
def get_fields(self):
        ret = SortedDict()

        try:
            # URI field for get pk field
            pk_field = primary_key(self.cls.__class__)

            request = self.context['request']
            ret["href"] = AlchemyUriField(
                source=pk_field,
                path=request.build_absolute_uri(request.path),
                read_only=True,
            )
        except KeyNotFoundException:
            return super(AlchemyListSerializer, self).get_fields()

        return ret 
Example #8
Source File: serializers.py    From drf-haystack with MIT License 6 votes vote down vote up
def get_objects(self, instance):
        """
        Return a list of objects matching the faceted result.
        """
        view = self.context["view"]
        queryset = self.context["objects"]

        page = view.paginate_queryset(queryset)
        if page is not None:
            serializer = view.get_facet_objects_serializer(page, many=True)
            return OrderedDict([
                ("count", self.get_count(queryset)),
                ("next", view.paginator.get_next_link()),
                ("previous", view.paginator.get_previous_link()),
                ("results", serializer.data)
            ])

        serializer = view.get_serializer(queryset, many=True)
        return serializer.data 
Example #9
Source File: query.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def _aggregate_select(self):
        """The SortedDict of aggregate columns that are not masked, and should
        be used in the SELECT clause.

        This result is cached for optimization purposes.
        """
        if self._aggregate_select_cache is not None:
            return self._aggregate_select_cache
        elif self.aggregate_select_mask is not None:
            self._aggregate_select_cache = SortedDict([
                (k,v) for k,v in self.aggregates.items()
                if k in self.aggregate_select_mask
            ])
            return self._aggregate_select_cache
        else:
            return self.aggregates 
Example #10
Source File: deletion.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def sort(self):
        sorted_models = []
        concrete_models = set()
        models = list(self.data)
        while len(sorted_models) < len(models):
            found = False
            for model in models:
                if model in sorted_models:
                    continue
                dependencies = self.dependencies.get(model._meta.concrete_model)
                if not (dependencies and dependencies.difference(concrete_models)):
                    sorted_models.append(model)
                    concrete_models.add(model._meta.concrete_model)
                    found = True
            if not found:
                return
        self.data = SortedDict([(model, self.data[model])
                                for model in sorted_models]) 
Example #11
Source File: base.py    From avos with Apache License 2.0 6 votes vote down vote up
def get_panel_groups(self):
        registered = copy.copy(self._registry)
        panel_groups = []

        # Gather our known panels
        if self._panel_groups is not None:
            for panel_group in self._panel_groups.values():
                for panel in panel_group:
                    registered.pop(panel.__class__)
                panel_groups.append((panel_group.slug, panel_group))

        # Deal with leftovers (such as add-on registrations)
        if len(registered):
            slugs = [panel.slug for panel in registered.values()]
            new_group = PanelGroup(self,
                                   slug="other",
                                   name=_("Other"),
                                   panels=slugs)
            panel_groups.append((new_group.slug, new_group))
        return SortedDict(panel_groups) 
Example #12
Source File: actions.py    From devops with MIT License 6 votes vote down vote up
def get_actions(self):
        if self.actions is None:
            return SortedDict()

        actions = [self.get_action(action) for action in self.global_actions]

        for klass in self.admin_view.__class__.mro()[::-1]:
            class_actions = getattr(klass, 'actions', [])
            if not class_actions:
                continue
            actions.extend(
                [self.get_action(action) for action in class_actions])

        # get_action might have returned None, so filter any of those out.
        actions = filter(None, actions)

        # Convert the actions into a SortedDict keyed by name.
        actions = SortedDict([
            (name, (ac, name, desc, icon))
            for ac, name, desc, icon in actions
        ])

        return actions 
Example #13
Source File: tabs.py    From avos with Apache License 2.0 6 votes vote down vote up
def get_volumes_data(self):
        volumes = self._get_volumes(search_opts={'all_tenants': True})
        instances = self._get_instances(search_opts={'all_tenants': True})
        volume_ids_with_snapshots = self._get_volumes_ids_with_snapshots(
            search_opts={'all_tenants': True})
        self._set_volume_attributes(
            volumes, instances, volume_ids_with_snapshots)

        # Gather our tenants to correlate against IDs
        try:
            tenants, has_more = keystone.tenant_list(self.request)
        except Exception:
            tenants = []
            msg = _('Unable to retrieve volume project information.')
            exceptions.handle(self.request, msg)

        tenant_dict = SortedDict([(t.id, t) for t in tenants])
        for volume in volumes:
            tenant_id = getattr(volume, "os-vol-tenant-attr:tenant_id", None)
            tenant = tenant_dict.get(tenant_id, None)
            volume.tenant_name = getattr(tenant, "name", None)

        return volumes 
Example #14
Source File: views.py    From avos with Apache License 2.0 6 votes vote down vote up
def get_initial(self):
        profile = self._get_object()
        # Set project name
        tenant_dict = _get_tenant_list(self.request)
        try:
            bindings = api.neutron.profile_bindings_list(
                self.request, 'network')
        except Exception:
            msg = _('Failed to obtain network profile binding')
            redirect = self.success_url
            exceptions.handle(self.request, msg, redirect=redirect)
        bindings_dict = datastructures.SortedDict(
            [(b.profile_id, b.tenant_id) for b in bindings])
        project_id = bindings_dict.get(profile.id)
        project = tenant_dict.get(project_id)
        project_name = getattr(project, 'name', project_id)
        return {'profile_id': profile['id'],
                'name': profile['name'],
                'segment_range': profile['segment_range'],
                'segment_type': profile['segment_type'],
                'physical_network': profile['physical_network'],
                'sub_type': profile['sub_type'],
                'multicast_ip_range': profile['multicast_ip_range'],
                'project': project_name} 
Example #15
Source File: ceilometer.py    From avos with Apache License 2.0 6 votes vote down vote up
def _get_cinder_meters_info(self):
        """Returns additional info for each meter

        That will be used for augmenting the Ceilometer meter
        """

        # TODO(lsmola) Unless the Ceilometer will provide the information
        # below, I need to define it as a static here. I will be joining this
        # to info that I am able to obtain from Ceilometer meters, hopefully
        # some day it will be supported all.
        return datastructures.SortedDict([
            ('volume', {
                'label': '',
                'description': _("Duration of volume"),
            }),
            ('volume.size', {
                'label': '',
                'description': _("Size of volume"),
            }),
        ]) 
Example #16
Source File: ceilometer.py    From avos with Apache License 2.0 6 votes vote down vote up
def _get_kwapi_meters_info(self):
        """Returns additional info for each meter

        That will be used for augmenting the Ceilometer meter
        """

        # TODO(lsmola) Unless the Ceilometer will provide the information
        # below, I need to define it as a static here. I will be joining this
        # to info that I am able to obtain from Ceilometer meters, hopefully
        # some day it will be supported all.
        return datastructures.SortedDict([
            ('energy', {
                'label': '',
                'description': _("Amount of energy"),
            }),
            ('power', {
                'label': '',
                'description': _("Power consumption"),
            }),
        ]) 
Example #17
Source File: neutron.py    From avos with Apache License 2.0 6 votes vote down vote up
def list(self, all_tenants=False, **search_opts):
        if not all_tenants:
            tenant_id = self.request.user.tenant_id
            # In Neutron, list_floatingips returns Floating IPs from
            # all tenants when the API is called with admin role, so
            # we need to filter them with tenant_id.
            search_opts['tenant_id'] = tenant_id
            port_search_opts = {'tenant_id': tenant_id}
        else:
            port_search_opts = {}
        fips = self.client.list_floatingips(**search_opts)
        fips = fips.get('floatingips')
        # Get port list to add instance_id to floating IP list
        # instance_id is stored in device_id attribute
        ports = port_list(self.request, **port_search_opts)
        port_dict = SortedDict([(p['id'], p) for p in ports])
        for fip in fips:
            self._set_instance_info(fip, port_dict.get(fip['port_id']))
        return [FloatingIp(fip) for fip in fips] 
Example #18
Source File: vpn.py    From avos with Apache License 2.0 6 votes vote down vote up
def _vpnservice_list(request, expand_subnet=False, expand_router=False,
                     expand_conns=False, **kwargs):
    vpnservices = neutronclient(request).list_vpnservices(
        **kwargs).get('vpnservices')
    if expand_subnet:
        subnets = neutron.subnet_list(request)
        subnet_dict = SortedDict((s.id, s) for s in subnets)
        for s in vpnservices:
            s['subnet_name'] = subnet_dict.get(s['subnet_id']).cidr
    if expand_router:
        routers = neutron.router_list(request)
        router_dict = SortedDict((r.id, r) for r in routers)
        for s in vpnservices:
            s['router_name'] = router_dict.get(s['router_id']).name_or_id
    if expand_conns:
        ipsecsiteconns = _ipsecsiteconnection_list(request, **kwargs)
        for s in vpnservices:
            s['ipsecsiteconns'] = [c.id for c in ipsecsiteconns
                                   if c.vpnservice_id == s['id']]
    return [VPNService(v) for v in vpnservices] 
Example #19
Source File: vpn.py    From avos with Apache License 2.0 6 votes vote down vote up
def _ipsecsiteconnection_list(request, expand_ikepolicies=False,
                              expand_ipsecpolicies=False,
                              expand_vpnservices=False, **kwargs):
    ipsecsiteconnections = neutronclient(request).list_ipsec_site_connections(
        **kwargs).get('ipsec_site_connections')
    if expand_ikepolicies:
        ikepolicies = _ikepolicy_list(request, **kwargs)
        policy_dict = SortedDict((p.id, p) for p in ikepolicies)
        for c in ipsecsiteconnections:
            c['ikepolicy_name'] = policy_dict.get(c['ikepolicy_id']).name_or_id
    if expand_ipsecpolicies:
        ipsecpolicies = _ipsecpolicy_list(request, **kwargs)
        policy_dict = SortedDict((p.id, p) for p in ipsecpolicies)
        for c in ipsecsiteconnections:
            c['ipsecpolicy_name'] = policy_dict.get(c['ipsecpolicy_id']
                                                    ).name_or_id
    if expand_vpnservices:
        vpnservices = _vpnservice_list(request, **kwargs)
        service_dict = SortedDict((s.id, s) for s in vpnservices)
        for c in ipsecsiteconnections:
            c['vpnservice_name'] = service_dict.get(c['vpnservice_id']
                                                    ).name_or_id
    return [IPSecSiteConnection(v) for v in ipsecsiteconnections] 
Example #20
Source File: base.py    From avos with Apache License 2.0 6 votes vote down vote up
def __init__(self, request, **kwargs):
        super(TabGroup, self).__init__()
        if not hasattr(self, "tabs"):
            raise NotImplementedError('%s must declare a "tabs" attribute.'
                                      % self.__class__)
        if not self.slug:
            raise NotImplementedError('%s must declare a "slug" attribute.'
                                      % self.__class__)
        self.request = request
        self.kwargs = kwargs
        self._data = None
        tab_instances = []
        for tab in self.tabs:
            tab_instances.append((tab.slug, tab(self, request)))
        self._tabs = SortedDict(tab_instances)
        if self.sticky:
            self.attrs['data-sticky-tabs'] = 'sticky'
        if not self._set_active_tab():
            self.tabs_not_available() 
Example #21
Source File: ceilometer.py    From avos with Apache License 2.0 5 votes vote down vote up
def _get_glance_meters_info(self):
        """Returns additional info for each meter

        That will be used for augmenting the Ceilometer meter
        """

        # TODO(lsmola) Unless the Ceilometer will provide the information
        # below, I need to define it as a static here. I will be joining this
        # to info that I am able to obtain from Ceilometer meters, hopefully
        # some day it will be supported all.
        return datastructures.SortedDict([
            ('image', {
                'label': '',
                'description': _("Image existence check"),
            }),
            ('image.size', {
                'label': '',
                'description': _("Uploaded image size"),
            }),
            ('image.update', {
                'label': '',
                'description': _("Number of update on the image"),
            }),
            ('image.upload', {
                'label': '',
                'description': _("Number of upload of the image"),
            }),
            ('image.delete', {
                'label': '',
                'description': _("Number of delete on the image"),
            }),
            ('image.download', {
                'label': '',
                'description': _("Image is downloaded"),
            }),
            ('image.serve', {
                'label': '',
                'description': _("Image is served out"),
            }),
        ]) 
Example #22
Source File: test_leaks_dict.py    From pywbem with GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_leaks_Django_SortedDict_empty():
    """
    Test function with empty django SortedDict object.

    Note: Django's SortedDict has been removed from the django package as of
    version 1.9. This test requires django<1.9 to be installed and is skipped
    otherwise.
    """
    _ = Django_SortedDict() 
Example #23
Source File: fwaas.py    From avos with Apache License 2.0 5 votes vote down vote up
def _policy_get(request, policy_id, expand_rule):
    policy = neutronclient(request).show_firewall_policy(
        policy_id).get('firewall_policy')
    if expand_rule:
        policy_rules = policy['firewall_rules']
        if policy_rules:
            rules = _rule_list(request, expand_policy=False,
                               firewall_policy_id=policy_id)
            rule_dict = SortedDict((rule.id, rule) for rule in rules)
            policy['rules'] = [rule_dict.get(rule) for rule in policy_rules]
        else:
            policy['rules'] = []
    return Policy(policy) 
Example #24
Source File: forms.py    From django-superform with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _init_composite_fields(self):
        """
        Setup the forms and formsets.
        """
        # The base_composite_fields class attribute is the *class-wide*
        # definition of fields. Because a particular *instance* of the class
        # might want to alter self.composite_fields, we create
        # self.composite_fields here by copying base_composite_fields.
        # Instances should always modify self.composite_fields; they should not
        # modify base_composite_fields.
        self.composite_fields = copy.deepcopy(self.base_composite_fields)
        self.forms = OrderedDict()
        self.formsets = OrderedDict()
        for name, field in self.composite_fields.items():
            self._init_composite_field(name, field) 
Example #25
Source File: forms.py    From django-superform with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __new__(mcs, name, bases, attrs):
        # Collect composite fields from current class.
        current_fields = []
        for key, value in list(attrs.items()):
            if isinstance(value, CompositeField):
                current_fields.append((key, value))
                attrs.pop(key)
        current_fields.sort(key=lambda x: x[1].creation_counter)
        attrs['declared_composite_fields'] = OrderedDict(current_fields)

        new_class = super(DeclerativeCompositeFieldsMetaclass, mcs).__new__(
            mcs, name, bases, attrs)

        # Walk through the MRO.
        declared_fields = OrderedDict()
        for base in reversed(new_class.__mro__):
            # Collect fields from base class.
            if hasattr(base, 'declared_composite_fields'):
                declared_fields.update(base.declared_composite_fields)

            # Field shadowing.
            for attr, value in base.__dict__.items():
                if value is None and attr in declared_fields:
                    declared_fields.pop(attr)

        new_class.base_composite_fields = declared_fields
        new_class.declared_composite_fields = declared_fields

        return new_class 
Example #26
Source File: neutron.py    From avos with Apache License 2.0 5 votes vote down vote up
def list_targets(self):
        tenant_id = self.request.user.tenant_id
        ports = port_list(self.request, tenant_id=tenant_id)
        servers, has_more = nova.server_list(self.request)
        server_dict = SortedDict([(s.id, s.name) for s in servers])
        reachable_subnets = self._get_reachable_subnets(ports)
        if is_service_enabled(self.request,
                              config_name='enable_lb',
                              ext_name='lbaas'):
            # Also get the loadbalancer VIPs
            vip_dict = {v['port_id']: v['name']
                        for v in self.client.list_vips().get('vips', [])}
        else:
            vip_dict = {}

        targets = []
        for p in ports:
            # Remove network ports from Floating IP targets
            if p.device_owner.startswith('network:'):
                continue
            port_id = p.id
            server_name = server_dict.get(p.device_id) or vip_dict.get(port_id)

            for ip in p.fixed_ips:
                if ip['subnet_id'] not in reachable_subnets:
                    continue
                target = {'name': '%s: %s' % (server_name, ip['ip_address']),
                          'id': '%s_%s' % (port_id, ip['ip_address']),
                          'instance_id': p.device_id}
                targets.append(FloatingIpTarget(target))
        return targets 
Example #27
Source File: formset.py    From avos with Apache License 2.0 5 votes vote down vote up
def __init__(self, column, datum, form):
        self.form = form
        super(FormsetRow, self).__init__(column, datum)
        if self.cells == []:
            # We need to be able to handle empty rows, because there may
            # be extra empty forms in a formset. The original DataTable breaks
            # on this, because it sets self.cells to [], but later expects a
            # SortedDict. We just fill self.cells with empty Cells.
            cells = []
            for column in self.table.columns.values():
                cell = self.table._meta.cell_class(None, column, self)
                cells.append((column.name or column.auto, cell))
            self.cells = datastructures.SortedDict(cells) 
Example #28
Source File: base.py    From avos with Apache License 2.0 5 votes vote down vote up
def get_ajax_update_url(self):
        column = self.column
        table_url = column.table.get_absolute_url()
        params = urlencode(SortedDict([
            ("action", self.row.ajax_cell_action_name),
            ("table", column.table.name),
            ("cell_name", column.name),
            ("obj_id", column.table.get_object_id(self.datum))
        ]))

        return "%s?%s" % (table_url, params) 
Example #29
Source File: views.py    From avos with Apache License 2.0 5 votes vote down vote up
def _get_tenant_list(self):
        try:
            tenants, has_more = api.keystone.tenant_list(self.request)
        except Exception:
            tenants = []
            msg = _('Unable to retrieve instance project information.')
            exceptions.handle(self.request, msg)

        tenant_dict = SortedDict([(t.id, t) for t in tenants])
        return tenant_dict 
Example #30
Source File: base.py    From avos with Apache License 2.0 5 votes vote down vote up
def __init__(self, tab_group, request):
        super(TableTab, self).__init__(tab_group, request)
        if not self.table_classes:
            class_name = self.__class__.__name__
            raise NotImplementedError("You must define a table_class "
                                      "attribute on %s" % class_name)
        # Instantiate our table classes but don't assign data yet
        table_instances = [(table._meta.name,
                            table(request, **tab_group.kwargs))
                           for table in self.table_classes]
        self._tables = SortedDict(table_instances)
        self._table_data_loaded = False