-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
executable file
·175 lines (117 loc) · 6 KB
/
model.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""Models and database functions for Ratings project."""
from flask_sqlalchemy import SQLAlchemy
# This is the connection to the PostgreSQL database; we're getting
# this through the Flask-SQLAlchemy helper library. On this, we can
# find the `session` object, where we do most of our interactions
# (like committing, etc.)
db = SQLAlchemy()
categories = {
"Sports": ["sports", "olympics", "pro sports", "college sports", "action sports"],
"Science": ["science", "askscience", "biotech", "chemistry", "biology", "biochemistry","labrats" ],
"Pets": ["aww", "cats", "catgifs", "dogs", "pets", "doggifs", "animalsbeingderps"],
"Wild Animals": ["wildlife", "wildliferehab", "babyelephantgifs", "tigerpics" , "giraffes"],
"Local News": ["sanfrancisco", "burlingame", "bayarea", "sfbeer", "sfbayhousing"],
"World News": ["worldnews",'politics'],
"Movies": ['movies'],
"Humor":['funny','AdviceAnimals', 'Jokes'],
"Fun Facts":['todayilearned','science','space','explainlikeimfive','lifeprotips','YouShouldKnow'],
"Technology":['technology','Android',"Bitcoin","programming","apple"]
}
#####################################################################
# Model definitions
class User(db.Model):
"""User of MyNews website."""
__tablename__ = "users"
user_id = db.Column(db.Integer,
autoincrement=True,
primary_key=True)
firstname = db.Column(db.String(64), nullable=True)
lastname = db.Column(db.String(64),nullable=True)
email = db.Column(db.String(64), nullable=True)
password = db.Column(db.String(64), nullable=True)
categories = db.relationship("Category",
secondary="users_categories",
backref="users")
def __repr__(self):
"""Provide helpful representation on a user when printed."""
return "<User user_id=%s name=%s> lastname=%s" % (self.user_id,
self.email,self.lastname)
@classmethod
def instantiate_user(cls, firstname, lastname, email, password):
"""Instantiate a user as a member"""
new_user = User(firstname=firstname,
lastname=lastname,
email=email,
password=password)
db.session.add(new_user)
db.session.commit()
return new_user
class Category(db.Model):
"""Categories which users can choose from"""
__tablename__="categories"
category_id = db.Column(db.Integer,
autoincrement=True,
primary_key=True)
category_name = db.Column(db.String(35), nullable=True)
subreddit_search = db.Column(db.String(300), nullable=True)
def __repr__(self):
"""Show category and associated id """
return "<Category ID=%d Category=%s>" % (self.category_id,self.category_name)
class UserCategory(db.Model):
"""A table to link users and their interests"""
__tablename__ = 'users_categories'
user_category_id = db.Column(db.Integer,
autoincrement=True,
primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
category_id = db.Column(db.Integer, db.ForeignKey('categories.category_id'))
def __repr__(self):
"""Table to associate user_id and category_id's...each have their own association id"""
return "UserCategory=%d User=%d Category=%d" %(self.user_category_id,self.user_id,self.category_id)
@classmethod
def instantiate_usercategory(cls,user_id,interest_list):
""""Make an association table for the member and their interests."""
for interest in interest_list:
association = UserCategory(user_id=user_id,category_id=interest)
db.session.add(association)
db.session.commit()
return association
def make_test_data():
"""populate a db with test data; used in testing"""
# make a couple users
lori = User(firstname='lori', lastname='bard', email='lori@bardfamily.org', password = "lori")
junior = User(firstname='junior', lastname='bard', email='ls@fmail.com', password = 'junior')
rusty = User(firstname='rusty', lastname='cat', email='rusty@bardfamiy.org', password='rusty')
# We need to add to the session or it won't ever be stored
db.session.add_all([lori, junior, rusty])
# make a couple categories
pets = Category(category_name='Pets', subreddit_search=["aww", "cats", "catgifs", "dogs", "pets", "doggifs", "animalsbeingderps"])
sports = Category(category_name='Sports', subreddit_search=["sports", "olympics", "pro sports", "college sports", "action sports"])
# We need to add to the session or it won't ever be stored
db.session.add_all([pets, sports])
db.session.flush()
# make a couple association table enries
lori_pets = UserCategory(user_id=lori.user_id, category_id=pets.category_id)
rusty_pets = UserCategory(user_id=rusty.user_id, category_id=pets.category_id)
junior_pets = UserCategory(user_id=junior.user_id, category_id=pets.category_id)
junior_sports = UserCategory(user_id=junior.user_id, category_id=sports.category_id)
# We need to add to the session or it won't ever be stored
db.session.add_all([lori_pets,rusty_pets,junior_pets,junior_sports])
db.session.commit()
#####################################################################
# Helper functions
def connect_to_db(app, db_uri='postgresql:///subreddits'):
"""Connect the database to our Flask app."""
# Configure to use our PostgreSQL database
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
app.config['SQLALCHEMY_ECHO'] = True
db.app = app
db.init_app(app)
if __name__ == "__main__":
# As a convenience, if we run this module interactively, it will
# leave you in a state of being able to work with the database
# directly.
from server import app
from server import r
connect_to_db(app)
print "Connected to DB"