views.py 2.86 KB
import gzip
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from common.decorators import render
from dictionary.models import Vocabulary
from export.forms import ExportForm, MagicQualifierForm
from export.lexeme_export import LexemeExport


@permission_required('dictionary.export_lexemes')
@render()
def export(request):
    if request.GET:
        form = ExportForm(data=request.GET)
        if form.is_valid():
            data = {
                'vocabs': [v.id for v in form.cleaned_data['vocabs']],
                'antivocabs': [v.id for v in form.cleaned_data['antivocabs']],
                'variant': form.cleaned_data['variant'].id,
            }
            # data['excluding_qualifiers'] = [
            #     q.pk for q in form.cleaned_data['excluding_qualifiers']]
            magic_ids = set()
            magic_qualifiers = []
            normal_qualifiers = []
            for key in request.GET:
                split_key = key.split('-')
                if key.startswith('magic') and split_key[0] not in magic_ids:
                    i, name = split_key
                    magic_ids.add(i)
                    magic_form = MagicQualifierForm(prefix=i, data=request.GET)
                    if magic_form.is_valid():
                        regex = magic_form.cleaned_data['regex']
                        if regex:
                            magic_qualifiers.append(
                                (
                                    regex,
                                    magic_form.cleaned_data['qualifier'].pk))
                        else:
                            normal_qualifiers.append(
                                magic_form.cleaned_data['qualifier'].pk)
            data['magic_qualifiers'] = magic_qualifiers
            data['excluding_qualifiers'] = normal_qualifiers
            data['refl'] = form.cleaned_data['refl']
            data['commonness'] = form.cleaned_data['commonness']
            ###
            response = HttpResponse(content_type='application/x-gzip')
            export_gz = gzip.GzipFile(fileobj=response, mode='w')
            LexemeExport(data, export_gz).export()
            filename = 'eksport.tab.gz'
            response['Content-Disposition'] = (
                'attachment; filename=%s' % filename)
            return response
    else:
        form = ExportForm()
    vocabs = {}
    for v in Vocabulary.objects.all():
        vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
    js_vars = {
        'vocabs': vocabs,
        'ajax_new_qualifier_row': reverse('magic_qualifier_row'),
        'ajax_save_export_data': reverse('save_export_data'),
        'ajax_get_export_data': reverse('get_export_data'),
        'ajax_delete_export_data': reverse('delete_export_data'),
    }
    return {'form': form, 'js_vars': js_vars}