trivial: apply black

This commit is contained in:
Frédéric Péters 2021-01-11 19:05:23 +01:00
parent cb7edde0e1
commit 917a485d7b
12 changed files with 131 additions and 73 deletions

View File

@ -16,11 +16,14 @@
import django.apps
class AppConfig(django.apps.AppConfig):
name = 'passerelle_montpellier_sig'
def get_urls(self):
from . import urls
return urls.urlpatterns
default_app_config = 'passerelle_montpellier_sig.AppConfig'

View File

@ -2,6 +2,7 @@ from django.contrib import admin
from .models import MontpellierSig
@admin.register(MontpellierSig)
class MontpellierSigAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}

View File

@ -1,3 +1 @@
INSTALLED_APPS += (
'passerelle_montpellier_sig',
)
INSTALLED_APPS += ('passerelle_montpellier_sig',)

View File

@ -3,6 +3,7 @@ from django import forms
from .models import MontpellierSig
class MontpellierSigForm(forms.ModelForm):
class Meta:
model = MontpellierSig

View File

@ -14,15 +14,35 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name='MontpellierSig',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
(
'id',
models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True),
),
('title', models.CharField(verbose_name='Title', max_length=50)),
('slug', models.SlugField(verbose_name='Identifier', unique=True)),
('description', models.TextField(verbose_name='Description')),
('service_url', models.CharField(help_text='SIG Web Service URL', max_length=128, verbose_name='Service URL')),
('verify_cert', models.BooleanField(default=True, verbose_name='Check HTTPS Certificate validity')),
(
'service_url',
models.CharField(
help_text='SIG Web Service URL', max_length=128, verbose_name='Service URL'
),
),
(
'verify_cert',
models.BooleanField(default=True, verbose_name='Check HTTPS Certificate validity'),
),
('username', models.CharField(max_length=128, verbose_name='Username', blank=True)),
('password', models.CharField(max_length=128, verbose_name='Password', blank=True)),
('keystore', models.FileField(help_text='Certificate and private key in PEM format', upload_to=b'monpellier_sig', null=True, verbose_name='Keystore', blank=True)),
(
'keystore',
models.FileField(
help_text='Certificate and private key in PEM format',
upload_to=b'monpellier_sig',
null=True,
verbose_name='Keystore',
blank=True,
),
),
('users', models.ManyToManyField(to='base.ApiUser', blank=True)),
],
options={

View File

@ -14,6 +14,19 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='montpelliersig',
name='log_level',
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'NOTSET', b'NOTSET'), (b'DEBUG', b'DEBUG'), (b'INFO', b'INFO'), (b'WARNING', b'WARNING'), (b'ERROR', b'ERROR'), (b'CRITICAL', b'CRITICAL'), (b'FATAL', b'FATAL')]),
field=models.CharField(
default=b'NOTSET',
max_length=10,
verbose_name='Log Level',
choices=[
(b'NOTSET', b'NOTSET'),
(b'DEBUG', b'DEBUG'),
(b'INFO', b'INFO'),
(b'WARNING', b'WARNING'),
(b'ERROR', b'ERROR'),
(b'CRITICAL', b'CRITICAL'),
(b'FATAL', b'FATAL'),
],
),
),
]

View File

@ -9,19 +9,19 @@ from passerelle.utils.jsonresponse import APIError
class MontpellierSig(BaseResource):
service_url = models.CharField(max_length=128, blank=False,
verbose_name=_('Service URL'),
help_text=_('SIG Web Service URL'))
verify_cert = models.BooleanField(default=True,
verbose_name=_('Check HTTPS Certificate validity'))
username = models.CharField(max_length=128, blank=True,
verbose_name=_('Username'))
password = models.CharField(max_length=128, blank=True,
verbose_name=_('Password'))
keystore = models.FileField(upload_to='monpellier_sig', null=True,
blank=True,
verbose_name=_('Keystore'),
help_text=_('Certificate and private key in PEM format'))
service_url = models.CharField(
max_length=128, blank=False, verbose_name=_('Service URL'), help_text=_('SIG Web Service URL')
)
verify_cert = models.BooleanField(default=True, verbose_name=_('Check HTTPS Certificate validity'))
username = models.CharField(max_length=128, blank=True, verbose_name=_('Username'))
password = models.CharField(max_length=128, blank=True, verbose_name=_('Password'))
keystore = models.FileField(
upload_to='monpellier_sig',
null=True,
blank=True,
verbose_name=_('Keystore'),
help_text=_('Certificate and private key in PEM format'),
)
category = _('Geographic information system')
@ -44,10 +44,9 @@ class MontpellierSig(BaseResource):
try:
resp = requests.get(self.service_url + '/adresse/rest/' + endpoint, **kwargs)
except requests.exceptions.RequestException as e:
raise APIError('SIG error: %s' % e)
raise APIError('SIG error: %s' % e)
if not resp.ok:
raise APIError('endpoint %r returned status code: %r' % (endpoint,
resp.status_code))
raise APIError('endpoint %r returned status code: %r' % (endpoint, resp.status_code))
try:
return resp.json()
except Exception as e:

View File

@ -9,9 +9,21 @@ from .views import *
urlpatterns = [
url(r'^(?P<slug>[\w,-]+)/communes$', CommunesView.as_view(), name='montpellier-sig-communes'),
url(r'^(?P<slug>[\w,-]+)/voies/(?P<insee>\d+)$', VoiesView.as_view(), name='montpellier-sig-voies'),
url(r'^(?P<slug>[\w,-]+)/voies/(?P<insee>\d+)/(?P<nom_rue>[\w ]+)/numero$', VoiesCommuneView.as_view(), name='montpellier-voies-commune'),
url(r'^(?P<slug>[\w,-]+)/voiecommune/(?P<nom_rue>[\w ]+)$', VoieCommuneView.as_view(), name='montpellier-sig-voiecommune'),
url(
r'^(?P<slug>[\w,-]+)/voies/(?P<insee>\d+)/(?P<nom_rue>[\w ]+)/numero$',
VoiesCommuneView.as_view(),
name='montpellier-voies-commune',
),
url(
r'^(?P<slug>[\w,-]+)/voiecommune/(?P<nom_rue>[\w ]+)$',
VoieCommuneView.as_view(),
name='montpellier-sig-voiecommune',
),
url(r'^(?P<slug>[\w,-]+)/reverse$', AdresseView.as_view(), name='montpellier-sig-adresse'),
url(r'^(?P<slug>[\w,-]+)/quartier/(?P<insee>\d+)/(?P<nom_rue>[\w ]+)/(?P<numero>\d+)/$', DistrictView.as_view(), name='montpellier-sig-district'),
url(
r'^(?P<slug>[\w,-]+)/quartier/(?P<insee>\d+)/(?P<nom_rue>[\w ]+)/(?P<numero>\d+)/$',
DistrictView.as_view(),
name='montpellier-sig-district',
),
url(r'^(?P<slug>[\w,-]+)/viewer/$', ViewerUrlView.as_view(), name='montpellier-sig-viewer'),
]

View File

@ -31,46 +31,49 @@ prefix_map = {
'ENCL': 'ENCLOS',
'ESP': 'ESPLANADE',
'ESPA': 'ESPACE',
'GR': '', # "GR GRAND-RUE JEAN MOULIN"
'GR': '', # "GR GRAND-RUE JEAN MOULIN"
'IMP': 'IMPASSE',
'JARD': 'JARDIN',
'MAIL': '', # "MAIL LE GRAND MAIL"
'MAIL': '', # "MAIL LE GRAND MAIL"
'PARC': 'PARC',
'PARV': '', # "PARV PARVIS DE LA LEGION D HONNEUR"
'PARV': '', # "PARV PARVIS DE LA LEGION D HONNEUR"
'PAS': 'PASSAGE',
'PL': 'PLACE',
'PLAN': 'PLAN',
'PONT': 'PONT',
'QUA': 'QUAI',
'R': 'RUE',
'RAMB': '', # "RAMB RAMBLA DES CALISSONS"
'RAMB': '', # "RAMB RAMBLA DES CALISSONS"
'RPT': 'ROND-POINT',
'RTE': 'ROUTE',
'SQ': 'SQUARE',
'TSSE': '', # "TSSE TERRASSE DES ALLEES DU BOIS"
'TSSE': '', # "TSSE TERRASSE DES ALLEES DU BOIS"
'TUN': 'TUNNEL',
'VIAD': 'VIADUC',
'VOI': 'VOIE',
}
def prefix_cleanup(name):
if not name:
return ''
name = name.strip()
for prefix, full in prefix_map.items():
if name.startswith(prefix + ' '):
name = (full + name[len(prefix):]).strip()
name = (full + name[len(prefix) :]).strip()
return name
def get_original_prefix(name):
if not name:
return ''
name = name.strip()
for prefix, full in prefix_map.items():
if name.startswith(full + ' '):
name = (prefix + name[len(full):]).strip()
name = (prefix + name[len(full) :]).strip()
return name.upper()
def split_street(name):
if not name:
return '', ''
@ -122,6 +125,7 @@ COMMUNES = [
('34337', 'VILLENEUVE-LES-MAGUELONE'),
]
class CommunesView(View, SingleObjectMixin):
model = MontpellierSig
@ -172,13 +176,16 @@ class VoiesCommuneView(View, SingleObjectMixin):
"attributes": {"numero": 8, "nom_voie": "ALL DES CONDAMINES"}},
...]
"""
model = MontpellierSig
def get(self, request, *args, **kwargs):
insee = kwargs['insee']
nom_rue = get_original_prefix(kwargs['nom_rue'])
if 'q' in request.GET:
result = self.get_object().sig_request('commune/' + insee + '/voie/' + nom_rue + '/numero/' + request.GET['q'])
result = self.get_object().sig_request(
'commune/' + insee + '/voie/' + nom_rue + '/numero/' + request.GET['q']
)
else:
result = self.get_object().sig_request('commune/' + insee + '/voie/' + nom_rue + '/numero')
voies_communes = []
@ -186,8 +193,7 @@ class VoiesCommuneView(View, SingleObjectMixin):
return utils.response_for_json(request, {'data': voies_communes})
for i in result:
attrs = i['attributes']
voie = {'id': '%(numero)s %(nom_voie)s' % attrs,
'text': '%(numero)s %(nom_voie)s' % attrs}
voie = {'id': '%(numero)s %(nom_voie)s' % attrs, 'text': '%(numero)s %(nom_voie)s' % attrs}
if i.get('geometry'):
voie.update({'x': i['geometry'].get('x'), 'y': i['geometry'].get('y')})
voies_communes.append(voie)
@ -205,11 +211,14 @@ class VoieCommuneView(View, SingleObjectMixin):
return utils.response_for_json(request, {'data': voies_communes})
for i in result:
attrs = i['attributes']
voies_communes.append({'id': '%(nom_voie)s' % attrs,
'text': '%(nom_voie)s' % attrs,
'commune': attrs['commune'],
'insee': attrs['code_insee']
})
voies_communes.append(
{
'id': '%(nom_voie)s' % attrs,
'text': '%(nom_voie)s' % attrs,
'commune': attrs['commune'],
'insee': attrs['code_insee'],
}
)
voies_communes.sort(key=lambda x: x['insee'])
return utils.response_for_json(request, {'data': voies_communes})
@ -228,18 +237,20 @@ class AdresseView(View, SingleObjectMixin):
l_lon, l_lat = pyproj.transform(wgs84, lambert93, lon, lat)
except TypeError:
return HttpResponseBadRequest()
result = self.get_object().sig_request('adresse/%s/%s' %(l_lon, l_lat))
result = self.get_object().sig_request('adresse/%s/%s' % (l_lon, l_lat))
house_number, road = split_street(result.get('voie'))
address = {'road': road,
'house_number': house_number,
'city': result.get('commune'),
'neighbourhood': result.get('sousquartier'),
'postcode': result.get('codepostal'),
'suburb': result.get('quartier'),
'country': 'France',
address = {
'road': road,
'house_number': house_number,
'city': result.get('commune'),
'neighbourhood': result.get('sousquartier'),
'postcode': result.get('codepostal'),
'suburb': result.get('quartier'),
'country': 'France',
}
return utils.response_for_json(request, {'address': address})
class DistrictView(View, SingleObjectMixin):
model = MontpellierSig
@ -248,13 +259,15 @@ class DistrictView(View, SingleObjectMixin):
nom_rue = get_original_prefix(kwargs['nom_rue'])
numero = kwargs['numero']
uri = 'commune/%s/voie/%s/numero/%s' % (insee, nom_rue, numero)
uri = 'commune/%s/voie/%s/numero/%s' % (insee, nom_rue, numero)
result = self.get_object().sig_request(uri)
if isinstance(result, dict) and result.get('error'):
return utils.response_for_json(request, {'data': []})
if result:
r = result[0]
data = self.get_object().sig_request('adresse/%s/%s' %(r['geometry'].get('x'), r['geometry'].get('y')))
data = self.get_object().sig_request(
'adresse/%s/%s' % (r['geometry'].get('x'), r['geometry'].get('y'))
)
return utils.response_for_json(request, {'data': data})
return utils.response_for_json(request, {'data': []})
@ -276,5 +289,7 @@ class ViewerUrlView(View, SingleObjectMixin):
except TypeError:
return HttpResponseBadRequest()
area = l_lon-50, l_lat-50, l_lon+50, l_lat+50
return redirect('http://sig.montpellier-agglo.com/WebVilleServer/resources/index.html#extent:%s;%s;%s;%s' % area)
area = l_lon - 50, l_lat - 50, l_lon + 50, l_lat + 50
return redirect(
'http://sig.montpellier-agglo.com/WebVilleServer/resources/index.html#extent:%s;%s;%s;%s' % area
)

View File

@ -25,9 +25,9 @@ class eo_sdist(sdist):
def get_version():
'''Use the VERSION, if absent generates a version with git describe, if not
tag exists, take 0.0- and add the length of the commit log.
'''
"""Use the VERSION, if absent generates a version with git describe, if not
tag exists, take 0.0- and add the length of the commit log.
"""
if os.path.exists('VERSION'):
version_file = open('VERSION', 'r')
version = version_file.read()
@ -67,6 +67,7 @@ class compile_translations(Command):
curdir = os.getcwd()
try:
from django.core.management import call_command
for path, dirs, files in os.walk('passerelle_montpellier_sig'):
if 'locale' not in dirs:
continue
@ -107,15 +108,12 @@ setup(
'Programming Language :: Python',
'Programming Language :: Python :: 2',
],
install_requires=['django>=1.8, <2',
'pyproj',
'requests'
],
install_requires=['django>=1.8, <2', 'pyproj', 'requests'],
zip_safe=False,
cmdclass={
'build': build,
'compile_translations': compile_translations,
'install_lib': install_lib,
'sdist': eo_sdist,
}
},
)

View File

@ -3,15 +3,14 @@ import os
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
INSTALLED_APPS += (
'passerelle_montpellier_sig',
)
INSTALLED_APPS += ('passerelle_montpellier_sig',)
DATABASES = {
'default': {
'ENGINE': os.environ.get('DB_ENGINE', 'django.db.backends.sqlite3'),
'TEST': {
'NAME': 'passerelle-montpellier-sig-test-%s' % os.environ.get('BRANCH_NAME', '').replace('/', '-')[:63],
'NAME': 'passerelle-montpellier-sig-test-%s'
% os.environ.get('BRANCH_NAME', '').replace('/', '-')[:63],
},
}
}

View File

@ -12,7 +12,6 @@ from passerelle.utils.jsonresponse import APIError
class PrefixCleanupTestCase(TestCase):
def test_prefix_alle(self):
self.assertEqual(prefix_cleanup('ALL DE LA PAIX'), 'ALLEE DE LA PAIX')
@ -63,9 +62,10 @@ class PrefixCleanupTestCase(TestCase):
class ReverseGeolocTest(TestCase):
def test_get_rue(self):
self.assertEqual(split_street('17 bis R WILLIAM ET CATHERINE BOOTH'), ('17 bis', 'RUE WILLIAM ET CATHERINE BOOTH'))
self.assertEqual(
split_street('17 bis R WILLIAM ET CATHERINE BOOTH'), ('17 bis', 'RUE WILLIAM ET CATHERINE BOOTH')
)
def test_split_impasse(self):
self.assertEqual(split_street(' 5 IMP VILLEHARDOUIN'), ('5', 'IMPASSE VILLEHARDOUIN'))
@ -75,11 +75,10 @@ class ReverseGeolocTest(TestCase):
class ConnectionTest(TestCase):
def setUp(self):
self.connector, created = MontpellierSig.objects.get_or_create(title='hebe',
slug='hebe', description='hebe',
service_url='http://hebe.montpellier3m.fr')
self.connector, created = MontpellierSig.objects.get_or_create(
title='hebe', slug='hebe', description='hebe', service_url='http://hebe.montpellier3m.fr'
)
@httmock.all_requests
def hebe_connection_failed(url, request, *args, **kwargs):