Projet

Général

Profil

0001-environment-coding-style-29240.patch

Benjamin Dauvergne, 24 mai 2019 11:05

Télécharger (21,3 ko)

Voir les différences:

Subject: [PATCH 1/9] environment: coding style (#29240)

 hobo/environment/forms.py  | 26 ++++++++--
 hobo/environment/models.py | 99 +++++++++++++++++++++++---------------
 hobo/environment/urls.py   | 40 ++++++++++-----
 hobo/environment/utils.py  | 33 ++++++++++---
 hobo/environment/views.py  | 34 ++++++++++---
 5 files changed, 164 insertions(+), 68 deletions(-)
hobo/environment/forms.py
1
# hobo - portal to configure and deploy applications
2
# Copyright (C) 2015-2019  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
1 17
from django import forms
2 18
from django.conf import settings
3 19
from django.contrib import messages
4 20
from django.http import HttpResponseRedirect
5 21
from django.template.defaultfilters import slugify
6 22
from django.utils.translation import ugettext_lazy as _
7
from django.core.validators import validate_email
8 23

  
9 24

  
10 25
from .models import (Authentic, Wcs, Passerelle, Variable, Combo, Fargo, Welco,
......
12 27
from .utils import get_setting_variable
13 28

  
14 29
EXCLUDED_FIELDS = ('last_operational_check_timestamp',
15
        'last_operational_success_timestamp', 'secret_key', 'secondary')
30
                   'last_operational_success_timestamp', 'secret_key',
31
                   'secondary')
16 32

  
17 33

  
18 34
class BaseForm(forms.ModelForm):
......
29 45
        # choice that was selected as an additional, disabled, <select> widget.
30 46
        if self.instance.id and len(choices) > 1:
31 47
            self.fields['template_name_readonly'] = forms.fields.CharField(
32
                    label=_('Template'), required=False,
33
                    initial=self.instance.template_name)
48
                label=_('Template'), required=False,
49
                initial=self.instance.template_name)
34 50
            self.fields['template_name_readonly'].widget = forms.Select(choices=choices)
35 51
            self.fields['template_name_readonly'].widget.attrs['disabled'] = 'disabled'
36 52

  
......
116 132
        model = MandayeJS
117 133
        exclude = EXCLUDED_FIELDS
118 134

  
135

  
119 136
class ChronoForm(BaseForm):
120 137
    class Meta:
121 138
        model = Chrono
122 139
        exclude = EXCLUDED_FIELDS
123 140

  
141

  
124 142
class CorboForm(BaseForm):
125 143
    class Meta:
126 144
        model = Corbo
hobo/environment/models.py
1
# hobo - portal to configure and deploy applications
2
# Copyright (C) 2015-2019  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
1 17
import re
2 18
import datetime
3 19
import json
......
13 29
from django.utils.six.moves.urllib.parse import urlparse
14 30
from django.utils.timezone import now
15 31
from django.utils.translation import ugettext_lazy as _
32
from django.utils import six
16 33
from django.core.exceptions import ValidationError
17 34
from django.core.validators import URLValidator
18 35

  
......
23 40
from .mandayejs_app_settings import APP_SETTINGS_CLASSES, DEFAULT_APP_SETTINGS
24 41

  
25 42
SECRET_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
26

  
27 43
FLOAT_RE = re.compile(r'^\s*[0-9]+\.[0-9]+\s*')
28 44

  
29 45

  
30 46
class Variable(models.Model):
31 47
    name = models.CharField(max_length=100, verbose_name=_('name'))
32 48
    label = models.CharField(max_length=100, blank=True, verbose_name=_('label'))
33
    value = models.TextField(verbose_name=_('value'),
34
            blank=True,
35
            help_text=_('start with [ or { for a JSON document'))
49
    value = models.TextField(
50
        verbose_name=_('value'),
51
        blank=True,
52
        help_text=_('start with [ or { for a JSON document'))
36 53
    auto = models.BooleanField(default=False)
37 54
    service_type = models.ForeignKey(ContentType, null=True)
38 55
    service_pk = models.PositiveIntegerField(null=True)
......
81 98
    last_operational_success_timestamp = models.DateTimeField(null=True)
82 99
    last_update_timestamp = models.DateTimeField(auto_now=True, null=True)
83 100

  
84
    variables = GenericRelation(Variable,
85
            content_type_field='service_type', object_id_field='service_pk')
101
    variables = GenericRelation(
102
        Variable,
103
        content_type_field='service_type',
104
        object_id_field='service_pk')
86 105

  
87 106
    @classmethod
88 107
    def is_enabled(cls):
89 108
        return True
90 109

  
91 110
    def is_operational(self):
92
        return (self.last_operational_success_timestamp is not None and
93
                self.last_operational_success_timestamp == self.last_operational_check_timestamp)
111
        return (self.last_operational_success_timestamp is not None
112
                and self.last_operational_success_timestamp == self.last_operational_check_timestamp)
94 113

  
95 114
    def check_operational(self):
96 115
        once_now = now()
......
100 119
            response = requests.get(zone.href, timeout=10, allow_redirects=False)
101 120
            response.raise_for_status()
102 121
            self.last_operational_success_timestamp = once_now
103
        except requests.RequestException as e:
122
        except requests.RequestException:
104 123
            pass
105 124
        self.save(update_fields=('last_operational_check_timestamp', 'last_operational_success_timestamp'))
106 125

  
......
120 139

  
121 140
    def as_dict(self):
122 141
        as_dict = dict([(x, y) for (x, y) in self.__dict__.items()
123
                        if type(y) in (int, str, unicode)])
142
                        if isinstance(y, six.integer_types + six.string_types)])
124 143
        as_dict['base_url'] = self.get_base_url_path()
125 144
        as_dict['service-id'] = self.Extra.service_id
126 145
        as_dict['service-label'] = force_text(self.Extra.service_label)
......
225 244

  
226 245
class Authentic(ServiceBase):
227 246
    use_as_idp_for_self = models.BooleanField(
228
            verbose_name=_('Use as IdP'),
229
            default=False)
247
        verbose_name=_('Use as IdP'),
248
        default=False)
230 249

  
231 250
    class Meta:
232 251
        verbose_name = _('Authentic Identity Provider')
......
240 259

  
241 260
    def get_admin_zones(self):
242 261
        return [
243
                Zone(_('User Management'), 'users', self.get_base_url_path() + 'manage/users/'),
244
                Zone(_('Role Management'), 'roles', self.get_base_url_path() + 'manage/roles/'),
245
                ]
262
            Zone(_('User Management'), 'users', self.get_base_url_path() + 'manage/users/'),
263
            Zone(_('Role Management'), 'roles', self.get_base_url_path() + 'manage/roles/'),
264
        ]
246 265

  
247 266
    def get_saml_idp_metadata_url(self):
248 267
        return self.get_base_url_path() + 'idp/saml2/metadata'
......
267 286

  
268 287
    def get_admin_zones(self):
269 288
        return [
270
                Zone(self.title, 'webforms', self.get_base_url_path() + 'admin/'),
271
                ]
289
            Zone(self.title, 'webforms', self.get_base_url_path() + 'admin/'),
290
        ]
272 291

  
273 292
    def get_saml_sp_metadata_url(self):
274 293
        return self.get_base_url_path() + 'saml/metadata'
......
287 306

  
288 307
    def get_admin_zones(self):
289 308
        return [
290
                Zone(self.title, 'webservices', self.get_base_url_path() + 'manage/')
291
                ]
309
            Zone(self.title, 'webservices', self.get_base_url_path() + 'manage/')
310
        ]
292 311

  
293 312
    def get_saml_sp_metadata_url(self):
294 313
        return self.get_base_url_path() + 'accounts/mellon/metadata/'
......
310 329

  
311 330
    def get_admin_zones(self):
312 331
        return [
313
                Zone(self.title, 'portal', self.get_base_url_path() + 'manage/')
314
                ]
332
            Zone(self.title, 'portal', self.get_base_url_path() + 'manage/')
333
        ]
315 334

  
316 335
    def get_saml_sp_metadata_url(self):
317 336
        return self.get_base_url_path() + 'accounts/mellon/metadata/'
......
333 352

  
334 353
    def get_admin_zones(self):
335 354
        return [
336
                Zone(self.title, 'document-box', self.get_base_url_path() + 'admin/')
337
                ]
355
            Zone(self.title, 'document-box', self.get_base_url_path() + 'admin/')
356
        ]
338 357

  
339 358
    def get_saml_sp_metadata_url(self):
340 359
        return self.get_base_url_path() + 'accounts/mellon/metadata/'
......
352 371

  
353 372
    def get_admin_zones(self):
354 373
        return [
355
                Zone(self.title, 'multichannel-guichet', self.get_base_url_path() + 'admin/')
356
                ]
374
            Zone(self.title, 'multichannel-guichet', self.get_base_url_path() + 'admin/')
375
        ]
357 376

  
358 377
    def get_saml_sp_metadata_url(self):
359 378
        return self.get_base_url_path() + 'accounts/mellon/metadata/'
......
363 382

  
364 383

  
365 384
class MandayeJS(ServiceBase):
366
    site_app = models.CharField(_('Site Application'), max_length=128,
367
        choices = APP_SETTINGS_CLASSES,
368
        default = DEFAULT_APP_SETTINGS
369
    )
385
    site_app = models.CharField(
386
        _('Site Application'),
387
        max_length=128,
388
        choices=APP_SETTINGS_CLASSES,
389
        default=DEFAULT_APP_SETTINGS)
390

  
370 391
    class Meta:
371 392
        verbose_name = _('Authentication Reverse Proxy')
372 393
        ordering = ['title']
......
382 403

  
383 404
    def get_admin_zones(self):
384 405
        return [
385
                Zone(self.title, 'mandayejs', self.get_base_url_path() + '_mandaye/admin/')
386
                ]
406
            Zone(self.title, 'mandayejs', self.get_base_url_path() + '_mandaye/admin/')
407
        ]
387 408

  
388 409
    def get_saml_sp_metadata_url(self):
389
        return self.get_base_url_path()+ '_mandaye/accounts/mellon/metadata/'
410
        return self.get_base_url_path() + '_mandaye/accounts/mellon/metadata/'
390 411

  
391 412

  
392 413
class Chrono(ServiceBase):
......
402 423

  
403 424
    def get_admin_zones(self):
404 425
        return [
405
                Zone(self.title, 'calendar', self.get_base_url_path() + 'manage/')
406
                ]
426
            Zone(self.title, 'calendar', self.get_base_url_path() + 'manage/')
427
        ]
407 428

  
408 429
    def get_saml_sp_metadata_url(self):
409 430
        return self.get_base_url_path() + 'accounts/mellon/metadata/'
......
425 446

  
426 447
    def get_admin_zones(self):
427 448
        return [
428
                Zone(self.title, 'hobo', self.get_base_url_path())
429
                ]
449
            Zone(self.title, 'hobo', self.get_base_url_path())
450
        ]
430 451

  
431 452
    def get_saml_sp_metadata_url(self):
432 453
        return self.get_base_url_path() + 'accounts/mellon/metadata/'
......
452 473

  
453 474
    def get_admin_zones(self):
454 475
        return [
455
                Zone(self.title, 'corbo', self.get_base_url_path() + 'admin/')
456
                ]
476
            Zone(self.title, 'corbo', self.get_base_url_path() + 'admin/')
477
        ]
457 478

  
458 479
    def get_saml_sp_metadata_url(self):
459
        return self.get_base_url_path()+ 'accounts/mellon/metadata/'
480
        return self.get_base_url_path() + 'accounts/mellon/metadata/'
460 481

  
461 482
    def get_backoffice_menu_url(self):
462 483
        return self.get_base_url_path() + 'manage/menu.json'
hobo/environment/urls.py
1
# hobo - portal to configure and deploy applications
2
# Copyright (C) 2015-2019  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
1 17
from django.conf.urls import url
2 18

  
3
from .views import *
19
from . import views
4 20

  
5 21
urlpatterns = [
6
    url(r'^$', HomeView.as_view(), name='environment-home'),
7
    url(r'^variables$', VariablesView.as_view(), name='environment-variables'),
8
    url(r'^new-variable$', VariableCreateView.as_view(), name='new-variable',),
9
    url(r'^update-variable/(?P<pk>\w+)$', VariableUpdateView.as_view(),
22
    url(r'^$', views.HomeView.as_view(), name='environment-home'),
23
    url(r'^variables$', views.VariablesView.as_view(), name='environment-variables'),
24
    url(r'^new-variable$', views.VariableCreateView.as_view(), name='new-variable',),
25
    url(r'^update-variable/(?P<pk>\w+)$', views.VariableUpdateView.as_view(),
10 26
        name='update-variable'),
11
    url(r'^delete-variable/(?P<pk>\w+)$', VariableDeleteView.as_view(),
27
    url(r'^delete-variable/(?P<pk>\w+)$', views.VariableDeleteView.as_view(),
12 28
        name='delete-variable'),
13 29
    url(r'^check_operational/(?P<service>\w+)/(?P<slug>[\w-]+)$',
14
        operational_check_view, name='operational-check'),
15
    url(r'^new-(?P<service>\w+)$', ServiceCreateView.as_view(), name='create-service'),
16
    url(r'^save-(?P<service>\w+)/(?P<slug>[\w-]+)$', ServiceUpdateView.as_view(), name='save-service'),
17
    url(r'^delete-(?P<service>\w+)/(?P<slug>[\w-]+)$', ServiceDeleteView.as_view(), name='delete-service'),
30
        views.operational_check_view, name='operational-check'),
31
    url(r'^new-(?P<service>\w+)$', views.ServiceCreateView.as_view(), name='create-service'),
32
    url(r'^save-(?P<service>\w+)/(?P<slug>[\w-]+)$', views.ServiceUpdateView.as_view(), name='save-service'),
33
    url(r'^delete-(?P<service>\w+)/(?P<slug>[\w-]+)$', views.ServiceDeleteView.as_view(), name='delete-service'),
18 34

  
19 35
    url(r'^new-variable-(?P<service>\w+)/(?P<slug>[\w-]+)$',
20
        VariableCreateView.as_view(), name='new-variable-service',),
21
    url(r'^debug.json$', debug_json, name='debug-json'),
36
        views.VariableCreateView.as_view(), name='new-variable-service',),
37
    url(r'^debug.json$', views.debug_json, name='debug-json'),
22 38
]
hobo/environment/utils.py
1
# hobo - portal to configure and deploy applications
2
# Copyright (C) 2015-2019  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
1 17
from django.conf import settings
2 18
from django.core.urlresolvers import reverse
3 19
from django.db import connection
......
12 28
        installed_services.extend(available_service.objects.all())
13 29
    return installed_services
14 30

  
31

  
15 32
def get_operational_services():
16 33
    return [x for x in get_installed_services() if x.is_operational()]
17 34

  
35

  
18 36
def get_installed_services_dict():
19
    from .models import AVAILABLE_SERVICES, Variable
37
    from .models import Variable
20 38
    hobo_service = []
21 39
    build_absolute_uri = None
22 40
    if hasattr(connection, 'get_tenant') and hasattr(connection.get_tenant(), 'build_absolute_uri'):
......
37 55
        }]
38 56
    return {
39 57
        'services': hobo_service + [x.as_dict() for x in get_installed_services()],
40
        'variables': dict(((v.name, v.json)
41
            for v in Variable.objects.filter(service_pk__isnull=True))),
42
        }
58
        'variables': {v.name: v.json for v in Variable.objects.filter(service_pk__isnull=True)}
59
    }
43 60

  
44 61

  
45 62
class Zone:
......
55 72

  
56 73
def get_setting_variable(name):
57 74
    from .models import Variable
58
    variable, created = Variable.objects.get_or_create(name=name,
59
            defaults={'auto': True, 'value': settings.VARIABLE_SETTINGS_DEFAULTS.get(name) or ''})
75
    variable, created = Variable.objects.get_or_create(
76
        name=name,
77
        defaults={
78
            'auto': True,
79
            'value': settings.VARIABLE_SETTINGS_DEFAULTS.get(name) or ''
80
        })
60 81
    return variable
hobo/environment/views.py
1
# hobo - portal to configure and deploy applications
2
# Copyright (C) 2015-2019  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
1 17
import json
2 18
import string
3 19

  
......
26 42
        context = super(HomeView, self).get_context_data(**kwargs)
27 43
        context['url_template'] = settings.SERVICE_URL_TEMPLATE
28 44
        context['available_services'] = [
29
                AvailableService(x) for x in AVAILABLE_SERVICES if x.is_enabled()]
45
            AvailableService(x) for x in AVAILABLE_SERVICES if x.is_enabled()
46
        ]
30 47
        context['installed_services'] = [x for x in utils.get_installed_services() if not x.secondary]
31 48
        return context
32 49

  
......
36 53

  
37 54
    def get_context_data(self, **kwargs):
38 55
        context = super(VariablesView, self).get_context_data(**kwargs)
39
        context['variables'] = Variable.objects.filter(auto=False,
40
                service_pk__isnull=True).order_by('label')
56
        context['variables'] = Variable.objects.filter(auto=False, service_pk__isnull=True).order_by('label')
41 57
        return context
42 58

  
43 59

  
......
68 84
            }
69 85
        try:
70 86
            self.object = Variable.objects.get(
71
                    name=form.instance.name,
72
                    **service_kwargs)
87
                name=form.instance.name,
88
                **service_kwargs)
73 89
        except Variable.DoesNotExist:
74 90
            self.object = form.save()
75 91
        else:
......
114 130

  
115 131
    def get_initial(self):
116 132
        initial = super(ServiceCreateView, self).get_initial()
117
        initial['base_url'] = string.Template(settings.SERVICE_URL_TEMPLATE
118
                ).substitute({'app': self.model.Extra.service_id})
133
        initial['base_url'] = (
134
            string.Template(settings.SERVICE_URL_TEMPLATE)
135
            .substitute({'app': self.model.Extra.service_id})
136
        )
119 137
        initial['slug'] = self.model.Extra.service_default_slug
120 138
        return initial
121 139

  
......
168 186
                return form_class
169 187
        return None
170 188

  
189

  
171 190
class ServiceDeleteView(DeleteView):
172 191
    success_url = reverse_lazy('environment-home')
173 192
    template_name = 'environment/generic_confirm_delete.html'
......
181 200
                return service.objects.get(slug=service_slug)
182 201
        return None
183 202

  
203

  
184 204
def operational_check_view(request, service, slug, **kwargs):
185 205

  
186 206
    for klass in AVAILABLE_SERVICES:
187
-