initdb.py
2.14 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import argparse
import re
import string
import sys
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from orm import Base, Student, Test, Question
# SIIUE names have alien strings like "(TE)" and are sometimes capitalized
# We remove them so that students dont keep asking what it means
def fix(name):
return string.capwords(re.sub('\(.*\)', '', name).strip())
# ===========================================================================
# Parse command line options
argparser = argparse.ArgumentParser(description='Create new database from a CSV file (SIIUE format)')
argparser.add_argument('--db', default='students.db', type=str, help='database filename')
argparser.add_argument('csvfile', nargs='?', type=str, default='', help='CSV filename')
args = argparser.parse_args()
# ===========================================================================
engine = create_engine('sqlite:///{}'.format(args.db), echo=False)
# Criate schema if needed
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
# --- start session ---
try:
session = Session()
# add administrator and fake student accounts
session.add_all([
Student(id='0', name='Professor', password=''),
Student(id='student1', name='Student1', password=''),
Student(id='student2', name='Student2', password=''),
Student(id='student3', name='Student3', password=''),
Student(id='student4', name='Student4', password=''),
Student(id='student5', name='Student5', password=''),
])
# add enrolled students from csv file
if args.csvfile:
try:
csvreader = csv.DictReader(open(args.csvfile, encoding='iso-8859-1'), delimiter=';', quotechar='"')
except EnvironmentError:
print('CSV file "{0}" not found!'.format(args.csvfile))
else:
session.add_all([Student(id=r['N.º'], name=fix(r['Nome']), password='') for r in csvreader])
session.commit()
except Exception:
session.rollback()
print('Erro: Dados já existentes na base de dados?')
sys.exit(1)
# --- end session ---