summaryrefslogtreecommitdiff
path: root/chimere/management/commands/chimere_import.py
blob: faddd5e9c99c644049ef3acb0af146f55d5df993 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import datetime, time
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ObjectDoesNotExist

from chimere.models import Importer
from chimere import tasks

class Command(BaseCommand):
    args = '<import_id>'
    help = "Launch import from an external source. Import configuration must "\
           "be beforehand inserted in the database with the web admin."
    option_list = BaseCommand.option_list + (
        make_option('--all',
            action='store_true',
            dest='all',
            default=False,
            help='Update all imports set to be automatically updated'),
        )


    def handle(self, *args, **options):
        importers = []
        if options['all']:
            importers = Importer.objects.filter(automatic_update=True).all()
        elif args and args[0]:
            try:
                importers = [Importer.objects.get(pk=int(args[0]))]
            except (ValueError, ObjectDoesNotExist):
                raise CommandError("Import with ID '%s' doesn't exist." % \
                                                                        args[0])
        else:
            imports = dict([(imp.pk, imp)
                       for imp in Importer.objects.order_by('pk').all()])
            while not importers:
                self.stdout.write('* Choose the import: \n')
                for k in imports:
                    self.stdout.write(' %s\n' % unicode(imports[k]).encode(
                                                             'ascii', 'ignore'))
                self.stdout.flush()
                self.stdout.write('\nImport ID: ')
                v = raw_input()
                try:
                    importers = [Importer.objects.get(pk=int(v))]
                except (ValueError, ObjectDoesNotExist):
                    self.stdout.write("Import with ID '%s' doesn't exist.\n\n" \
                                      % v)
        for imprt in importers:
            pending_state = unicode(tasks.IMPORT_MESSAGES['import_pending'][0])
            imprt.state = pending_state
            imprt.save()
            tasks.importing(imprt.pk)
            self.stdout.write("Import '%d' in progress...\n" % imprt.pk)
            self.stdout.flush()
            state = pending_state
            while state == pending_state:
                time.sleep(1)
                state = Importer.objects.get(pk=int(imprt.pk)).state
            self.stdout.write(state + '\n')