From d345fb08c92335ba4998c4e1b6812abec51f5a59 Mon Sep 17 00:00:00 2001 From: Serghei Mihai Date: Sat, 20 Jun 2015 16:05:38 +0200 Subject: [PATCH] csv files data source (#5896) --- passerelle/apps/csvdatasource/__init__.py | 26 +++++ passerelle/apps/csvdatasource/admin.py | 3 + passerelle/apps/csvdatasource/forms.py | 16 +++ .../apps/csvdatasource/migrations/0001_initial.py | 32 ++++++ .../0002_csvdatasource_columns_titles.py | 20 ++++ .../apps/csvdatasource/migrations/__init__.py | 0 passerelle/apps/csvdatasource/models.py | 124 +++++++++++++++++++++ .../csvdatasource/csvdatasource_detail.html | 52 +++++++++ passerelle/apps/csvdatasource/tests.py | 3 + passerelle/apps/csvdatasource/urls.py | 27 +++++ passerelle/apps/csvdatasource/views.py | 52 +++++++++ passerelle/settings.py | 1 + passerelle/static/css/style.css | 3 + 13 files changed, 359 insertions(+) create mode 100644 passerelle/apps/csvdatasource/__init__.py create mode 100644 passerelle/apps/csvdatasource/admin.py create mode 100644 passerelle/apps/csvdatasource/forms.py create mode 100644 passerelle/apps/csvdatasource/migrations/0001_initial.py create mode 100644 passerelle/apps/csvdatasource/migrations/0002_csvdatasource_columns_titles.py create mode 100644 passerelle/apps/csvdatasource/migrations/__init__.py create mode 100644 passerelle/apps/csvdatasource/models.py create mode 100644 passerelle/apps/csvdatasource/templates/csvdatasource/csvdatasource_detail.html create mode 100644 passerelle/apps/csvdatasource/tests.py create mode 100644 passerelle/apps/csvdatasource/urls.py create mode 100644 passerelle/apps/csvdatasource/views.py diff --git a/passerelle/apps/csvdatasource/__init__.py b/passerelle/apps/csvdatasource/__init__.py new file mode 100644 index 0000000..4d8e365 --- /dev/null +++ b/passerelle/apps/csvdatasource/__init__.py @@ -0,0 +1,26 @@ +# passerelle.contrib.csvdatasource +# Copyright (C) 2015 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 . + +import django.apps + +class AppConfig(django.apps.AppConfig): + name = 'csvdatasource' + + def get_after_urls(self): + from . import urls + return urls.urlpatterns + +default_app_config = 'csvdatasource.AppConfig' diff --git a/passerelle/apps/csvdatasource/admin.py b/passerelle/apps/csvdatasource/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/passerelle/apps/csvdatasource/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/passerelle/apps/csvdatasource/forms.py b/passerelle/apps/csvdatasource/forms.py new file mode 100644 index 0000000..5b2d30a --- /dev/null +++ b/passerelle/apps/csvdatasource/forms.py @@ -0,0 +1,16 @@ +from django.utils.text import slugify +from django import forms + +from .models import CsvDataSource + + +class CsvDataSourceForm(forms.ModelForm): + + class Meta: + model = CsvDataSource + exclude = ('slug', 'users') + + def save(self, commit=True): + if not self.instance.slug: + self.instance.slug = slugify(self.instance.title) + return super(CsvDataSourceForm, self).save(commit=commit) diff --git a/passerelle/apps/csvdatasource/migrations/0001_initial.py b/passerelle/apps/csvdatasource/migrations/0001_initial.py new file mode 100644 index 0000000..d76fc07 --- /dev/null +++ b/passerelle/apps/csvdatasource/migrations/0001_initial.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('base', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='CsvDataSource', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('title', models.CharField(max_length=50)), + ('slug', models.SlugField()), + ('description', models.TextField()), + ('csv_file', models.FileField(upload_to=b'csv')), + ('key_column', models.IntegerField(default=0)), + ('text_column', models.IntegerField(default=1)), + ('cache_duration', models.IntegerField(default=600, verbose_name='Cache duration in seconds')), + ('users', models.ManyToManyField(to='base.ApiUser', blank=True)), + ], + options={ + 'verbose_name': 'CSV File', + }, + bases=(models.Model,), + ), + ] diff --git a/passerelle/apps/csvdatasource/migrations/0002_csvdatasource_columns_titles.py b/passerelle/apps/csvdatasource/migrations/0002_csvdatasource_columns_titles.py new file mode 100644 index 0000000..5b901dd --- /dev/null +++ b/passerelle/apps/csvdatasource/migrations/0002_csvdatasource_columns_titles.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('csvdatasource', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='csvdatasource', + name='columns_titles', + field=models.CharField(help_text='in "[column index]:[column title],..." format', max_length=256, verbose_name='Optional column titles', blank=True), + preserve_default=True, + ), + ] diff --git a/passerelle/apps/csvdatasource/migrations/__init__.py b/passerelle/apps/csvdatasource/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/passerelle/apps/csvdatasource/models.py b/passerelle/apps/csvdatasource/models.py new file mode 100644 index 0000000..2a52775 --- /dev/null +++ b/passerelle/apps/csvdatasource/models.py @@ -0,0 +1,124 @@ +import re +import csv +import logging + +from django.db import models +from django.core.cache import cache +from django.utils.translation import ugettext_lazy as _ +from django.core.urlresolvers import reverse + +from passerelle.base.models import BaseResource + +logger = logging.getLogger(__name__) + +_CACHE_SENTINEL = object() + +class CsvError(Exception): + pass + + +class CsvDataSource(BaseResource): + csv_file = models.FileField(upload_to='csv') + key_column = models.IntegerField(default=0) + text_column = models.IntegerField(default=1) + columns_titles = models.CharField(max_length=256, blank=True, + verbose_name=_('Optional column titles'), + help_text=_('in "[column index]:[column title],..." format')) + cache_duration = models.IntegerField(default=600, + verbose_name=_('Cache duration in seconds')) + + + category = _('Data Sources') + + class Meta: + verbose_name = 'CSV File' + + @classmethod + def get_verbose_name(cls): + return cls._meta.verbose_name + + @classmethod + def get_icon_class(cls): + return 'grid' + + @classmethod + def is_enabled(cls): + return True + + @classmethod + def get_add_url(cls): + return reverse('csvdatasource-add') + + def get_edit_url(self): + return reverse('csvdatasource-edit', kwargs={'slug': self.slug}) + + def get_delete_url(self): + return reverse('csvdatasource-delete', kwargs={'slug': self.slug}) + + def get_absolute_url(self): + return reverse('csvdatasource-detail', kwargs={'slug': self.slug}) + + def has_cache(self): + self.__content = cache.get(self.slug, _CACHE_SENTINEL) + return self.__content is not _CACHE_SENTINEL + + def set_cache(self, data): + cache.set(self.slug, data, self.cache_duration) + + @property + def content(self): + if self.has_cache(): + return cache.get(self.slug, _CACHE_SENTINEL) + self.__content = self.csv_file.read() + self.set_cache(self.__content) + return self.__content + + def get_data(self, id_row=None, columns=None, filter_criteria=None): + + def get_text(row, columns): + d = '' + for col in columns: + try: + d += row[int(col)] + ' ' + except ValueError: + raise CsvError(_('Wrong column format: %s') % col) + except IndexError: + raise CsvError(_('Unknown column: %s') % col) + return d.strip() + + def get_id(row, column=0): + try: + if column: + return unicode(row[int(column)], 'utf-8') + else: + return unicode(row[int(self.key_column)], 'utf-8') + except IndexError: + raise CsvError(_('Unexisting columns for id')) + except ValueError: + raise CsvError(_('Wrong id index: %s') % column) + + def filter_row(row, columns, filter_criteria): + for col in columns: + if filter_criteria in unicode(row[int(col)], 'utf-8'): + return True + + data = [] + dialect = csv.Sniffer().sniff(self.content[:1024]) + reader = csv.reader(self.content.splitlines(), dialect) + + if self.columns_titles: + captions = self.columns_titles.split(',') + else: + captions = [] + + for row in reader: + if filter_criteria and not filter_row(row, columns, filter_criteria): + continue + r = {'id': get_id(row, id_row), 'text': get_text(row, columns)} + for caption in captions: + index, title = caption.split(':') + r[title] = get_text(row, [index]) + data.append(r) + + data.sort(lambda x,y: cmp(x['text'], y['text'])) + return data diff --git a/passerelle/apps/csvdatasource/templates/csvdatasource/csvdatasource_detail.html b/passerelle/apps/csvdatasource/templates/csvdatasource/csvdatasource_detail.html new file mode 100644 index 0000000..dbd0f56 --- /dev/null +++ b/passerelle/apps/csvdatasource/templates/csvdatasource/csvdatasource_detail.html @@ -0,0 +1,52 @@ +{% extends "passerelle/base.html" %} +{% load i18n passerelle %} + + + +{% block appbar %} +

CSV - {{ object.title }}

+ +{% if perms.csvdatasource.change_csvdatasource %} +{% trans 'edit' %} +{% endif %} + +{% if perms.csvdatasource.delete_csvdatasource %} +{% trans 'delete' %} +{% endif %} +{% endblock %} + + + +{% block content %} +

+Data file : {{ object.csv_file.name }} +

+ +
+

{% trans 'Endpoints' %}

+ +
+ + +{% if perms.base.view_accessright %} +
+

{% trans "Security" %}

+ +

+{% trans 'Accessing the listings is open, but posting requests is limited to the following API users:' %} +

+ +{% access_rights_table resource=object permission='can_post_request' %} +{% endif %} + +
+ +{% endblock %} + diff --git a/passerelle/apps/csvdatasource/tests.py b/passerelle/apps/csvdatasource/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/passerelle/apps/csvdatasource/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/passerelle/apps/csvdatasource/urls.py b/passerelle/apps/csvdatasource/urls.py new file mode 100644 index 0000000..1bcd8cf --- /dev/null +++ b/passerelle/apps/csvdatasource/urls.py @@ -0,0 +1,27 @@ +from django.conf.urls import patterns, include, url +from django.contrib.auth.decorators import login_required + +from passerelle.urls_utils import decorated_includes, required, app_enabled + +from views import * + +public_urlpatterns = patterns('', + url(r'^(?P[\w,-]+)/$', CsvDataSourceDetailView.as_view(), name='csvdatasource-detail'), + url(r'^(?P[\w,-]+)/data$', CsvDataView.as_view(), name='csvdatasource-data'), +) + +management_urlpatterns = patterns('', + url(r'^add$', CsvDataSourceCreateView.as_view(), name='csvdatasource-add'), + url(r'^(?P[\w,-]+)/edit$', CsvDataSourceUpdateView.as_view(), name='csvdatasource-edit'), + url(r'^(?P[\w,-]+)/delete$', CsvDataSourceDeleteView.as_view(), name='csvdatasource-delete'), +) + + +urlpatterns = required( + app_enabled('csvdatasource'), + patterns('', + url(r'^csvdatasource/', include(public_urlpatterns)), + url(r'^manage/csvdatasource/', + decorated_includes(login_required, include(management_urlpatterns))), + ) +) diff --git a/passerelle/apps/csvdatasource/views.py b/passerelle/apps/csvdatasource/views.py new file mode 100644 index 0000000..359a088 --- /dev/null +++ b/passerelle/apps/csvdatasource/views.py @@ -0,0 +1,52 @@ +import json + +from django.core.urlresolvers import reverse +from django.views.generic.edit import CreateView, UpdateView, DeleteView +from django.views.generic.detail import DetailView, SingleObjectMixin +from django.views.generic.base import View + +from passerelle.base.views import ResourceView +from passerelle.utils import to_json + +from .models import CsvDataSource +from .forms import CsvDataSourceForm + + +class CsvDataSourceDetailView(DetailView): + model = CsvDataSource + + +class CsvDataSourceCreateView(CreateView): + model = CsvDataSource + template_name = 'passerelle/manage/service_form.html' + form_class = CsvDataSourceForm + + +class CsvDataSourceUpdateView(UpdateView): + model = CsvDataSource + template_name = 'passerelle/manage/service_form.html' + form_class = CsvDataSourceForm + + +class CsvDataSourceDeleteView(DeleteView): + model = CsvDataSource + template_name = 'passerelle/manage/service_confirm_delete.html' + + def get_success_url(self): + return reverse('manage-home') + + +class CsvDataView(View, SingleObjectMixin): + model = CsvDataSource + + @to_json('api') + def get(self, request, *args, **kwargs): + obj = self.get_object() + filter_criteria = request.GET.get('q') + id_col = request.GET.get('id_col') + columns = [request.GET.get('text_col', obj.text_column)] + text_cols = request.GET.get('text_cols') + if text_cols: + text_cols = text_cols.split(',') + columns = set(columns) | set(text_cols) + return obj.get_data(id_col, columns, filter_criteria) diff --git a/passerelle/settings.py b/passerelle/settings.py index 2e75677..4aa00db 100644 --- a/passerelle/settings.py +++ b/passerelle/settings.py @@ -108,6 +108,7 @@ INSTALLED_APPS = ( 'concerto', 'bdp', 'base_adresse', + 'csvdatasource', # backoffice templates and static 'gadjo', ) diff --git a/passerelle/static/css/style.css b/passerelle/static/css/style.css index 436cc1c..3ceb90b 100644 --- a/passerelle/static/css/style.css +++ b/passerelle/static/css/style.css @@ -32,3 +32,6 @@ li.bdp a:hover { background-image: url(icons/icon-bdp-hover.png); } li.gis a { background-image: url(icons/icon-gis.png); } li.gis a:hover { background-image: url(icons/icon-gis-hover.png); } + +li.grid a { background-image: url(icons/icon-grid.png); } +li.grid a:hover { background-image: url(icons/icon-grid-hover.png); } -- 2.1.4