-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
76 lines (65 loc) · 2.31 KB
/
models.py
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
69
70
71
72
73
74
75
76
#!usr/bin/python
from flask.ext.login import UserMixin
from peewee import *
from hashlib import md5
DATABASE = SqliteDatabase('classmates.db')
class BaseModel(Model):
'''Schema blueprint for other tables to inherit'''
class Meta:
database = DATABASE # make the tables in classmates.db
class Classmate(UserMixin, BaseModel):
'''Table with student information'''
username = CharField(max_length = 20, unique = True)
password = CharField(max_length = 18)
first_name = CharField(max_length = 20)
last_name = CharField(max_length = 20)
is_admin = BooleanField(default = False)
first = CharField(max_length = 20)
second = CharField(max_length = 20)
third = CharField(max_length = 20)
fourth = CharField(max_length = 20)
fifth = CharField(max_length = 20)
sixth = CharField(max_length = 20)
'''
Basically in SQL: CREATE TABLE Classmate ( id INTEGER AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(20) UNIQUE,
password VARCHAR(18),
first_name VARCHAR(20),
last_name VARCHAR(20),
is_admin BOOLEAN DEFAULT FALSE,
first VARCHAR(20),
second VARCHAR(20),
third VARCHAR(20),
fourth VARCHAR(20),
fifth VARCHAR(20),
sixth VARCHAR(20)
);
'''
# Note that peewee automatically creates an id row, so there's no need to actually declare it.
@classmethod # To allow creating a user without creating an instance of the class
def create_user(cls, username, password, first_name, last_name, first, second, third, fourth, fifth, sixth, admin = False):
'''add classmate to Classmate table. Note engineering students are permitted to take up to six clasess'''
try:
with DATABASE.transaction(): # Basically, try creating a user, if it works great, otherwise forget everything you just tried
cls.create(
first_name = first_name,
last_name = last_name,
username = username,
password = md5(password).hexdigest(),
first = first,
second = second,
third = third,
fourth = fourth,
fifth = fifth,
sixth = sixth,
is_admin = admin)
except IntegrityError:
raise ValueError('User already exists')
class Meta:
'''table design'''
order_by = ('last_name',)
def initialize():
'''Boot up database'''
DATABASE.connect()
DATABASE.create_tables([Classmate], safe = True)
DATABASE.close()