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
66
67
68
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Import departements and towns from csv file
"""
DELIMITER = ","
QUOTECHAR = '"'
import sys
import csv
sys.path.append('.')
from django.core.management import setup_environ
import settings
setup_environ(settings)
from optparse import OptionParser
from ishtar_common import models
def insert_department(value):
idx, label = value
if models.Department.objects.filter(number=idx).count():
return
models.Department(number=idx, label=label).save()
print idx, label, u" inserted"
def insert_town(value):
idx, label = value
if models.Town.objects.filter(numero_insee=idx).count():
return
try:
dpt = models.Departement.objects.get(number=idx[:2])
except:
return
models.Town(numero_insee=idx, name=label, departement=dpt).save()
print idx, label, u" inserted"
tables = {u"department":insert_department,
u"town":insert_town}
usage = u"usage: %%prog csv_file.csv table_name\n\n"\
u"Table name must be in: %s." % u", ".join(tables.keys())
parser = OptionParser(usage=usage)
(options, args) = parser.parse_args()
try:
assert len(args) == 2
except AssertionError:
parser.error(u"You must provide one csv file and the table name.")
try:
assert args[1] in tables.keys()
except AssertionError:
parser.error(u"Incorrect table name.")
try:
values = csv.reader(open(args[0], 'rb'), delimiter=DELIMITER,
quotechar=QUOTECHAR)
except (IOError):
parser.error(u"Incorrect CSV file.")
for value in values:
tables[args[1]](value)
|