示例#1
0
 def test_invalid_values(self):
     """
     If dictsort is passed something other than a list of dictionaries,
     fail silently.
     """
     self.assertEqual(dictsort([1, 2, 3], 'age'), '')
     self.assertEqual(dictsort('Hello!', 'age'), '')
     self.assertEqual(dictsort({'a': 1}, 'age'), '')
     self.assertEqual(dictsort(1, 'age'), '')
示例#2
0
    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        policy_name = kwargs['policy_name']
        try:
            policy = congress.policy_get(self.request, policy_name)
        except Exception as e:
            msg_args = {'policy_name': policy_name, 'error': e.message}
            msg = _('Unable to get policy "%(policy_name)s": '
                    '%(error)s') % msg_args
            LOG.error(msg)
            messages.error(self.request, msg)
            redirect = reverse('horizon:admin:policies:index')
            raise exceptions.Http302(redirect)
        context['policy'] = policy

        # Alphabetize and convert list of data source tables and columns into
        # JSON formatted string consumable by JavaScript. Do this here instead
        # of in the Create Rule form so that the tables and columns lists
        # appear in the HTML document before the JavaScript that uses them.
        all_tables = ds_utils.get_datasource_tables(self.request)
        sorted_datasources = dictsort(all_tables, 'datasource')
        tables = []
        for ds in sorted_datasources:
            datasource_tables = ds['tables']
            datasource_tables.sort()
            for table in ds['tables']:
                tables.append('%s%s%s' % (ds['datasource'],
                                          congress.TABLE_SEPARATOR, table))
        context['tables'] = json.dumps(tables)

        datasource_columns = ds_utils.get_datasource_columns(self.request)
        sorted_datasources = dictsort(datasource_columns, 'datasource')
        columns = []
        for ds in sorted_datasources:
            sorted_tables = dictsort(ds['tables'], 'table')
            for tbl in sorted_tables:
                # Ignore service-derived tables, which are already included.
                if congress.TABLE_SEPARATOR in tbl['table']:
                    continue
                table_columns = tbl['columns']
                if table_columns:
                    table_columns.sort()
                else:
                    # Placeholder name for column when the table has none.
                    table_columns = ['_']

                for column in table_columns:
                    columns.append('%s%s%s %s' % (ds['datasource'],
                                                  congress.TABLE_SEPARATOR,
                                                  tbl['table'], column))
        context['columns'] = json.dumps(columns)
        return context
示例#3
0
def sort_items_by_date(object_list, date_fields="date_published, timestamp, pub_date, date_submitted, date_created", recent_first=False):
  """
  Given a list of heterogeneous items (instances from several different models) and a list of
  possible date field names, sort the items by date. Any items in the list without a date field
  attribute will be left out of the results. Defaults to most recent items last, but accepts a
  recent_first argument to reverse the chronology.
  """
  date_field_list = date_fields.split(",")
  object_dict_list = []
  for object in object_list:
    if object:
      object_date_field = None
      for field in date_field_list:
        for f in object._meta.fields:
          if f.name == field:
            object_date_field = f.name
            break
        if object_date_field:
          object_dict = { 'date': getattr(object, object_date_field), 'object': object }
          object_dict_list.append(object_dict)
  
  if recent_first:
    sorted_item_dicts = dictsortreversed(object_dict_list, 'date')
  else:
    sorted_item_dicts = dictsort(object_dict_list, 'date')
  sorted_items = []
  for item in sorted_item_dicts:
    if item['object'] not in sorted_items:
      sorted_items.append(item['object'])
  return sorted_items
示例#4
0
    def test_dictsort(self):
        sorted_dicts = dictsort([{'age': 23, 'name': 'Barbara-Ann'},
                                 {'age': 63, 'name': 'Ra Ra Rasputin'},
                                 {'name': 'Jonny B Goode', 'age': 18}], 'age')

        self.assertEqual([sorted(dict.items()) for dict in sorted_dicts],
            [[('age', 18), ('name', 'Jonny B Goode')],
             [('age', 23), ('name', 'Barbara-Ann')],
             [('age', 63), ('name', 'Ra Ra Rasputin')]])

        # If it gets passed a list of something else different from
        # dictionaries it should fail silently
        self.assertEqual(dictsort([1, 2, 3], 'age'), '')
        self.assertEqual(dictsort('Hello!', 'age'), '')
        self.assertEqual(dictsort({'a': 1}, 'age'), '')
        self.assertEqual(dictsort(1, 'age'), '')
示例#5
0
 def test_sort_list_of_tuple_like_dicts(self):
     data = [
         {'0': 'a', '1': '42'},
         {'0': 'c', '1': 'string'},
         {'0': 'b', '1': 'foo'},
     ]
     expected = [
         {'0': 'a', '1': '42'},
         {'0': 'b', '1': 'foo'},
         {'0': 'c', '1': 'string'},
     ]
     self.assertEqual(dictsort(data, '0'), expected)
示例#6
0
 def save(self, force_insert=False, force_update=False):
   # Kind of ugly hack to account for the fact that Flickr doesn't provide creation dates for its photosets.
   # We'll just use the date_published of the oldest photo the set contains as the date_published for the gallery.
   if self.flickr_photoset and self.galleryphoto_set.all():
     from django.template.defaultfilters import dictsort
     galleryphotos = self.galleryphoto_set.all()
     photos = []
     for gp in galleryphotos:
       photos.append(gp.photo)
     oldest_photo = dictsort(photos, 'date_published')[0]
     self.date_published = oldest_photo.date_published
   super(Gallery, self).save(force_insert=force_insert, force_update=force_update)
示例#7
0
    def test_dictsort_complex_sorting_key(self):
        """
        Since dictsort uses template.Variable under the hood, it can sort
        on keys like 'foo.bar'.
        """
        data = [
            {'foo': {'bar': 1, 'baz': 'c'}},
            {'foo': {'bar': 2, 'baz': 'b'}},
            {'foo': {'bar': 3, 'baz': 'a'}},
        ]
        sorted_data = dictsort(data, 'foo.baz')

        self.assertEqual([d['foo']['bar'] for d in sorted_data], [3, 2, 1])
示例#8
0
    def test_sort(self):
        sorted_dicts = dictsort(
            [{'age': 23, 'name': 'Barbara-Ann'},
             {'age': 63, 'name': 'Ra Ra Rasputin'},
             {'name': 'Jonny B Goode', 'age': 18}],
            'age',
        )

        self.assertEqual(
            [sorted(dict.items()) for dict in sorted_dicts],
            [[('age', 18), ('name', 'Jonny B Goode')],
             [('age', 23), ('name', 'Barbara-Ann')],
             [('age', 63), ('name', 'Ra Ra Rasputin')]],
        )
示例#9
0
 def closest_spots(self, this_spot, mile_limit=25):
   """ 
   Returns the "num" closest spots to this one. Limits to spots within
   a given mile_limit, which defaults to 25 miles.
   """
   from django.template.defaultfilters import dictsort
   spots_within_limit = self.within_radius_of_location(location=this_spot.location(), radius_miles=mile_limit)
   spot_dict_list = []
   for spot in spots_within_limit:
     if spot != this_spot:
       distance = this_spot._get_distance_to_spot(spot)
       direction = this_spot._get_compass_direction_to_spot(spot)
       spot_dict_list.append({ 'distance': float(distance), 'spot': spot, 'direction': direction })
   return dictsort(spot_dict_list, 'distance')
示例#10
0
文件: tests.py 项目: GT-Master/DNDC
    def test_dictsort(self):
        sorted_dicts = dictsort([{
            'age': 23,
            'name': 'Barbara-Ann'
        }, {
            'age': 63,
            'name': 'Ra Ra Rasputin'
        }, {
            'name': 'Jonny B Goode',
            'age': 18
        }], 'age')

        self.assertEqual([sorted(dict.items()) for dict in sorted_dicts], [[
            ('age', 18), ('name', 'Jonny B Goode')
        ], [('age', 23),
            ('name', 'Barbara-Ann')], [('age', 63),
                                       ('name', 'Ra Ra Rasputin')]])

        # If it gets passed a list of something else different from
        # dictionaries it should fail silently
        self.assertEqual(dictsort([1, 2, 3], 'age'), '')
        self.assertEqual(dictsort('Hello!', 'age'), '')
        self.assertEqual(dictsort({'a': 1}, 'age'), '')
        self.assertEqual(dictsort(1, 'age'), '')
示例#11
0
 def get_closest_places(self, mile_limit=25):
   """ 
   Return a dictionary with the keys "distance" (in miles) and "place", sorted by distance ascending.
   Smaller distances are places closer to the this GeolocatedItem. Defaults to only showing places within
   25 miles of the original location. 
   """
   from django.template.defaultfilters import dictsort
   import math
   place_dict_list = []
   for place in Place.objects.all():
     if place != self.content_object:
       if place.location():
         distance = self.get_distance_from_location(place.location())
         if distance <= mile_limit:
           place_dict = { 'distance': float(distance), 'place': place }
           place_dict_list.append(place_dict)
   return dictsort(place_dict_list, 'distance')
示例#12
0
 def lookups(self, request, model_admin):
     vals = ()
     val_list = []
     cs = ContentType.objects.filter(logentry__action_flag__in=[1, 2, 3]).distinct()
     exclude_function = RaPermissionWidgetExclude()
     for c in cs:
         model = c.model_class()
         if model:
             if not exclude_function(model):
                 # vals += ((c.pk, force_text(model._meta.verbose_name_plural)),)
                 val_list.append({
                     'name': capfirst(force_text(model._meta.verbose_name_plural)),
                     'value': ((c.pk, capfirst(force_text(model._meta.verbose_name_plural))),)
                 })
     ordered_list = dictsort(val_list, 'name')
     for o in ordered_list:
         vals += o['value']
     return vals
示例#13
0
 def closest_spots(self, this_spot, mile_limit=25):
     """ 
 Returns the "num" closest spots to this one. Limits to spots within
 a given mile_limit, which defaults to 25 miles.
 """
     from django.template.defaultfilters import dictsort
     spots_within_limit = self.within_radius_of_location(
         location=this_spot.location(), radius_miles=mile_limit)
     spot_dict_list = []
     for spot in spots_within_limit:
         if spot != this_spot:
             distance = this_spot._get_distance_to_spot(spot)
             direction = this_spot._get_compass_direction_to_spot(spot)
             spot_dict_list.append({
                 'distance': float(distance),
                 'spot': spot,
                 'direction': direction
             })
     return dictsort(spot_dict_list, 'distance')
示例#14
0
    def test_sort(self):
        sorted_dicts = dictsort(
            [{
                'age': 23,
                'name': 'Barbara-Ann'
            }, {
                'age': 63,
                'name': 'Ra Ra Rasputin'
            }, {
                'name': 'Jonny B Goode',
                'age': 18
            }],
            'age',
        )

        self.assertEqual(
            [sorted(dict.items()) for dict in sorted_dicts],
            [[('age', 18),
              ('name', 'Jonny B Goode')], [('age', 23),
                                           ('name', 'Barbara-Ann')],
             [('age', 63), ('name', 'Ra Ra Rasputin')]],
        )
示例#15
0
def sort_by(queryset, filter_list_string):
    filter_list = filter_list_string.split(", ")
    return dictsort(dictsort(queryset, filter_list[0]), filter_list[1])
示例#16
0
 def test_sort_list_of_tuples(self):
     data = [('a', '42'), ('c', 'string'), ('b', 'foo')]
     expected = [('a', '42'), ('b', 'foo'), ('c', 'string')]
     self.assertEqual(dictsort(data, 0), expected)
示例#17
0
 def test_sort_list_of_tuples(self):
     data = [("a", "42"), ("c", "string"), ("b", "foo")]
     expected = [("a", "42"), ("b", "foo"), ("c", "string")]
     self.assertEqual(dictsort(data, 0), expected)
示例#18
0
 def test_sort_list_of_tuples(self):
     data = [('a', '42'), ('c', 'string'), ('b', 'foo')]
     expected = [('a', '42'), ('b', 'foo'), ('c', 'string')]
     self.assertEqual(dictsort(data, 0), expected)