Projet

Général

Profil

0002-maps-add-option-to-specify-properties-to-include-in-.patch

Frédéric Péters, 06 juillet 2018 14:28

Télécharger (9,26 ko)

Voir les différences:

Subject: [PATCH 2/2] maps: add option to specify properties to include in
 geojson (#25094)

 .../migrations/0007_auto_20180706_1345.py     |  20 ++++
 combo/apps/maps/models.py                     |  19 +++-
 combo/apps/maps/static/js/combo.map.js        |   6 +-
 tests/test_maps_cells.py                      | 105 +++++++++++++++++-
 4 files changed, 146 insertions(+), 4 deletions(-)
 create mode 100644 combo/apps/maps/migrations/0007_auto_20180706_1345.py
combo/apps/maps/migrations/0007_auto_20180706_1345.py
1
# -*- coding: utf-8 -*-
2
# Generated by Django 1.11.12 on 2018-07-06 11:45
3
from __future__ import unicode_literals
4

  
5
from django.db import migrations, models
6

  
7

  
8
class Migration(migrations.Migration):
9

  
10
    dependencies = [
11
        ('maps', '0006_auto_20180627_0841'),
12
    ]
13

  
14
    operations = [
15
        migrations.AddField(
16
            model_name='maplayer',
17
            name='properties',
18
            field=models.CharField(blank=True, help_text='List of properties', max_length=500, verbose_name='Properties'),
19
        ),
20
    ]
combo/apps/maps/models.py
102 102
    include_user_identifier = models.BooleanField(
103 103
            _('Include user identifier in request'),
104 104
            default=True)
105
    properties = models.CharField(_('Properties'), max_length=500, blank=True,
106
            help_text=_('List of properties'))
105 107

  
106 108
    class Meta:
107 109
        ordering = ('label',)
......
165 167
        else:
166 168
            features = data
167 169

  
170
        properties = []
171
        if self.properties:
172
            properties = [x.strip() for x in self.properties.split(',')]
173
            for feature in features:
174
                if 'display_fields' in feature['properties']:
175
                    # w.c.s. content, filter fields on varnames
176
                    feature['properties']['display_fields'] = [
177
                            x for x in feature['properties']['display_fields']
178
                            if x.get('varname') in properties]
179
                else:
180
                    # classic geojson, filter properties
181
                    feature['properties'] = dict(
182
                        [x for x in feature['properties'].items() if x[0] in properties])
183

  
168 184
        if request and request.GET.get('distance'):
169 185
            distance = float(request.GET['distance'])
170 186
            center_lat = float(request.GET['lat'])
......
202 218
                'icon_colour': self.icon_colour,
203 219
                'label': self.label,
204 220
                'icon': self.icon,
205
                'identifier': self.slug
221
                'identifier': self.slug,
222
                'properties': properties,
206 223
            }
207 224
        return features
208 225

  
combo/apps/maps/static/js/combo.map.js
32 32
                                    popup += $popup_field.html();
33 33
                                });
34 34
                            } else {
35
                                var ordered_keys = feature.properties.layer.properties;
36
                                if (! ordered_keys) {
37
                                    ordered_keys = Object.keys(properties).sort();
38
                                }
35 39
                                var properties = feature.properties;
36
                                $.each(Object.keys(properties).sort(), function(idx, field) {
40
                                $.each(ordered_keys, function(idx, field) {
37 41
                                    // exclude object type properties
38 42
                                    if (typeof(properties[field]) !== 'object') {
39 43
                                        var $popup_field = $('<div><div class="popup-field property-' + field + '"></span><span class="field-value"></span></div></div>');
tests/test_maps_cells.py
22 22
    {
23 23
      "type": "Feature",
24 24
      "properties": {
25
         "name": "Foo"
25
         "name": "Foo",
26
         "extra": "Baz"
26 27
      },
27 28
      "geometry": {
28 29
        "type": "Point",
......
35 36
    {
36 37
      "type": "Feature",
37 38
      "properties": {
38
         "name": "Bar"
39
         "name": "Bar",
40
         "extra": "Baz"
39 41
      },
40 42
      "geometry": {
41 43
        "type": "Point",
......
48 50
  ]
49 51
}'''
50 52

  
53
SAMPLE_WCS_GEOJSON_CONTENT = '''{
54
  "type": "FeatureCollection",
55
  "features": [
56
     {
57
       "type" : "Feature",
58
       "geometry" : {
59
          "type" : "Point",
60
          "coordinates" : [
61
             6.175303,
62
             48.684512
63
          ]
64
       },
65
       "properties" : {
66
          "name" : "Test - n°144-4",
67
          "view_label" : "Voir",
68
          "status_name" : "Foo",
69
          "display_fields" : [
70
             {
71
                "varname" : "id",
72
                "html_value" : "144-4",
73
                "value" : "144-4",
74
                "label" : "Numéro"
75
             },
76
             {
77
                "varname" : null,
78
                "html_value" : "toto",
79
                "value" : "toto",
80
                "label" : "toto"
81
             }
82
          ]
83
        }
84
     }
85
  ]
86
}'''
87

  
88

  
89

  
51 90
@pytest.fixture
52 91
def user():
53 92
    try:
......
243 282

  
244 283
        resp = client.get(reverse('mapcell-geojson', kwargs={'cell_id': cell.id}) + '?lng=2.54&lat=48.84&distance=100')
245 284
        assert len(json.loads(resp.content)['features']) == 0
285

  
286
def test_get_geojson_properties(layer, user):
287
    page = Page(title='xxx', slug='new', template_name='standard')
288
    page.save()
289
    cell = Map(page=page, placeholder='content', order=0, public=True)
290
    cell.title = 'Map'
291
    cell.save()
292
    layer.save()
293
    cell.layers.add(layer)
294

  
295
    with mock.patch('combo.utils.requests_wrapper.RequestsSession.request') as requests_get:
296
        layer.geojson_url = 'http://example.org/geojson?t1'
297
        layer.save()
298
        requests_get.return_value = mock.Mock(
299
                content=SAMPLE_GEOJSON_CONTENT,
300
                json=lambda: json.loads(SAMPLE_GEOJSON_CONTENT),
301
                status_code=200)
302
        resp = client.get(reverse('mapcell-geojson', kwargs={'cell_id': cell.id}))
303
        features = json.loads(resp.content)['features']
304
        assert 'name' in features[0]['properties']
305
        assert 'extra' in features[0]['properties']
306
        assert features[0]['properties']['layer']['properties'] == []
307

  
308
    with mock.patch('combo.utils.requests_wrapper.RequestsSession.request') as requests_get:
309
        layer.geojson_url = 'http://example.org/geojson?t2'
310
        layer.properties = 'name, hop'
311
        layer.save()
312
        requests_get.return_value = mock.Mock(
313
                content=SAMPLE_GEOJSON_CONTENT,
314
                json=lambda: json.loads(SAMPLE_GEOJSON_CONTENT),
315
                status_code=200)
316
        resp = client.get(reverse('mapcell-geojson', kwargs={'cell_id': cell.id}))
317
        features = json.loads(resp.content)['features']
318
        assert 'name' in features[0]['properties']
319
        assert 'extra' not in features[0]['properties']
320
        assert features[0]['properties']['layer']['properties'] == ['name', 'hop']
321

  
322
    with mock.patch('combo.utils.requests_wrapper.RequestsSession.request') as requests_get:
323
        layer.geojson_url = 'http://example.org/geojson?t3'
324
        layer.properties = ''
325
        layer.save()
326
        requests_get.return_value = mock.Mock(
327
                content=SAMPLE_WCS_GEOJSON_CONTENT,
328
                json=lambda: json.loads(SAMPLE_WCS_GEOJSON_CONTENT),
329
                status_code=200)
330
        resp = client.get(reverse('mapcell-geojson', kwargs={'cell_id': cell.id}))
331
        features = json.loads(resp.content)['features']
332
        assert len(features[0]['properties']['display_fields']) == 2
333
        assert features[0]['properties']['layer']['properties'] == []
334

  
335
    with mock.patch('combo.utils.requests_wrapper.RequestsSession.request') as requests_get:
336
        layer.geojson_url = 'http://example.org/geojson?t4'
337
        layer.properties = 'id'
338
        layer.save()
339
        requests_get.return_value = mock.Mock(
340
                content=SAMPLE_WCS_GEOJSON_CONTENT,
341
                json=lambda: json.loads(SAMPLE_WCS_GEOJSON_CONTENT),
342
                status_code=200)
343
        resp = client.get(reverse('mapcell-geojson', kwargs={'cell_id': cell.id}))
344
        features = json.loads(resp.content)['features']
345
        assert len(features[0]['properties']['display_fields']) == 1
346
        assert features[0]['properties']['layer']['properties'] == ['id']
246
-