passerelle-imio-liege-lisrue/passerelle_imio_liege_lisrue/views.py

92 lines
3.0 KiB
Python

# passerelle-imio-liege-lisrue - passerelle connector to Lisrue webservice
# Copyright (C) 2016 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import requests
import unicodedata
from django.views.generic.detail import SingleObjectMixin, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.base import View, RedirectView
from django.core.urlresolvers import reverse
from django.http import HttpResponseBadRequest
from passerelle import utils
from .models import ImioLiegeLisrue
from .forms import ImioLiegeLisrueForm
class SigCreateView(CreateView):
model = ImioLiegeLisrue
form_class = ImioLiegeLisrueForm
template_name = 'passerelle/manage/service_form.html'
class SigUpdateView(UpdateView):
model = ImioLiegeLisrue
form_class = ImioLiegeLisrueForm
class SigDeleteView(DeleteView):
model = ImioLiegeLisrue
def get_success_url(self):
return reverse('manage-home')
class SigDetailView(DetailView):
model = ImioLiegeLisrue
class VoiesView(View, SingleObjectMixin):
model = ImioLiegeLisrue
def get(self, request, *args, **kwargs):
url = self.get_object().service_url
if self.get_object().include_all_of_belgium:
url += 'jsonlisrue/'
else:
url += 'jsonlisrue2/'
if 'q' in request.GET and request.GET['q']:
q = unicodedata.normalize('NFKD', request.GET['q']).encode('ascii', 'ignore')
url += q.lower()
result = requests.get(url, headers={'Accept': 'application/json'},
verify=self.get_object().verify_cert).json()
if isinstance(result['rues'], list):
lisrues = result['rues']
elif isinstance(result['rues'], dict) and 'return' in result['rues']:
lisrues = [result['rues']['return']]
else:
lisrues = []
streets = []
for item in lisrues:
if item.get('rue'):
street_label = item.get('rue')
elif item.get('libelleMinuscule'):
street_label = '%s %s' % (
item.get('particuleMinuscule') or '',
item.get('libelleMinuscule'))
else:
continue
streets.append({
'id': item.get('codeRue'),
'text': street_label.strip(),
})
return utils.response_for_json(request, {'data': streets})