Make descriptions unicode explicitely
[montanha:montanha.git] / generate-csv
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (©) 2010, 2012 Gustavo Noronha Silva
5 #
6 #  This program is free software: you can redistribute it and/or modify
7 #  it under the terms of the GNU Affero General Public License as
8 #  published by the Free Software Foundation, either version 3 of the
9 #  License, or (at your option) any later version.
10 #
11 #  This program is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #  GNU Affero General Public License for more details.
15 #
16 #  You should have received a copy of the GNU Affero General Public License
17 #  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 import optparse
20 import os.path
21 import csv
22 import sources
23 from models import *
24
25 import sys
26 if len(sys.argv) < 2:
27     print 'Tell me which house!'
28     sys.exit(1)
29
30 import os
31 appdir = os.path.dirname(__file__)
32 if not appdir:
33     appdir = '.'
34 appdir = os.path.abspath(appdir)
35
36
37 sys.path = [ appdir ] + sys.path
38
39
40 if __name__ == '__main__':
41     parser = optparse.OptionParser()
42     parser.add_option('-y', '--year', type='int', dest='year', help='Year to collect from.')
43
44     Session = models.initialize('sqlite:///data.db')
45     session = Session()
46     query = session.query(Expense.nature, Legislator.name, Legislator.party,
47                           Supplier.name.label('supplier'), Supplier.cnpj, Expense.number,
48                           Expense.date, Expense.expensed
49                           ).join('legislator').join('supplier').order_by('8')
50
51     outfile = open('dump.csv', 'wb')
52     outfile.write('\xef\xbb\xbf');
53     outcsv = csv.writer(outfile, 'excel-tab')
54
55     [ outcsv.writerow([
56                 curr.party,
57                 curr.name.encode('utf-8'),
58                 curr.number.encode('utf-8'),
59                 curr.nature.encode('utf-8'),
60                 curr.supplier.encode('utf-8'),
61                 "'" + curr.cnpj,
62                 curr.date,
63                 str(curr.expensed).replace('.', ','),
64                 curr.number.encode('utf-8')]) for curr in query ]
65
66     outfile.close()
67