forked from mhendri/buyrentsell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
372 lines (302 loc) · 11.8 KB
/
app.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
from flask import Flask
from flask import flash, redirect, render_template, request, session, abort, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
import random
import os
# from flask.ext.login import LoginManager
# for datetime
from datetime import datetime
# Database Imports
from sqlalchemy.orm import sessionmaker
# from tabledef import *
# # create enginer for database
# engine = create_engine('sqlite:///brs.db', echo=True)
app = Flask(__name__)
# set the secret key
app.secret_key = os.urandom(12)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///brs.db'
db = SQLAlchemy(app)
admin = Admin(app, name='BRS Admin', template_mode='bootstrap3')
global resultnum
resultnum = 0
################################################################################
## MODELS
################################################################################
##------------------------------------------------------------------------------
## User Model
##------------------------------------------------------------------------------
class User(db.Model):
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column('Firstname', db.String(120), unique=False)
lastname = db.Column('Lastname', db.String(120), unique=False)
email = db.Column('email', db.String(120), unique=True)
password = db.Column('password', db.String(15), unique=False)
phone = db.Column('phone', db.Integer, unique=False)
balance = db.Column('balance', db.Integer, unique=False)
active = db.Column('active', db.Boolean, unique=False)
############################################################################
## CONSTRUCTOR
############################################################################
def __init__(self, email="", password="", firstname="", lastname="", phone=""):
''' '''
self.firstname = firstname
self.lastname = lastname
self.email = email
self.password = password
self.phone = phone
self.balance = 0
# active is initially False
# user must be approved by superuser
self.active = False
############################################################################
## GETTERS
############################################################################
def get_first_name(self):
return self.firstname
def get_last_name(self):
return self.lastname
def get_email(self):
return self.email
def get_phone(self):
return self.phone
def get_balance(self):
return self.balance
############################################################################
## SETTERS
############################################################################
def set_email(self, email):
self.email = email
def set_phone(self, phone):
self.phone = phone
# unsure about this setter / may not be needed
def set_balance(self, balance):
self.balance = balance
def activate_user(self):
self.active = True
def suspend_user(self):
self.active = False
############################################################################
## OTHER METHODS
############################################################################
# adding money to account
def deposit(self, amount):
self.balance += amount
# removing money from account
def withdraw(self, amount):
if amount > self.balance:
# handle error case
print("Insufficient Funds to perform this transaction")
else:
self.balance -= amount
##------------------------------------------------------------------------------
## Posts Model
##------------------------------------------------------------------------------
class Post(db.Model):
__tablename__ = "Posts"
id = db.Column(db.Integer, primary_key=True)
userid = db.Column('userid', db.Integer, db.ForeignKey("Users.id"), unique = False)
title = db.Column('title', db.String(120), unique=False)
price = db.Column('price', db.Numeric(12,2), unique=False)
descr = db.Column('description', db.String(500), unique=False)
date = db.Column('date', db.DateTime)
category = db.Column('category', db.String(120))
isSold = db.Column('isSold', db.Boolean)
buyer = db.Column('buyer', db.String(120))
############################################################################
## CONSTRUCTOR
############################################################################
def __init__(self, userid=0, title="", price="", descr="", date=None, category=None):
self.userid = userid
self.title = title
self.price = price
self.descr = descr
if date is None:
date = datetime.utcnow()
self.date = date
self.category = category
self.isSold = False
############################################################################
## GETTERS
############################################################################
def getPostID(self):
return self.id
def getUserID(self):
return self.userid
def getTitle(self):
return self.title
def getPrice(self):
return self.price
def getDesc(self):
return self.desc
def getDate(self):
return self.date
def getCategory(self):
return self.category
def getIsSold(self):
return self.isSold
############################################################################
## SETTERS
############################################################################
def setTitle(self, title):
self.title = title
def setPrice(self, price):
self.price = price
def setDesc(self, desc):
self.desc = desc
def setCategory(self, category):
self.category = category
def markSold(self):
self.isSold = True
############################################################################
## OTHER METHODS
############################################################################
##------------------------------------------------------------------------------
## Flag Model
##------------------------------------------------------------------------------
class Flag(db.Model):
__tablename__ = "Flag"
flagid = db.Column(db.Integer, primary_key=True)
userid = db.Column('userid', db.Integer, db.ForeignKey("Users.id"), unique = False)
reason = db.Column('flag_reason', db.String(120), unique=False)
############################################################################
## CONSTRUCTOR
############################################################################
def __init__(self,userid=None, reason=""):
self.userid = userid
self.reason = reason
# Need to add few more things:
# buyer_id, (is_biddable, current_bid, time_limit), date_posted, is_reported, image
# Create Database
# db.create_all()
# to add mock data, add entries to dummy.py
# following conventions in that file
# then run `$ python dummy.py` from your shell to commit those changes
################################################################################
## FLASK-ADMIN
################################################################################
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Post, db.session))
admin.add_view(ModelView(Flag, db.session))
################################################################################
## ROUTES
################################################################################
# Set "homepage" to index.html
@app.route('/')
@app.route('/index')
def index():
if not session.get('logged_in'):
return render_template('index.html')
else:
#if logged_in, we should display show_entries
return render_template('index.html')
# Logging In
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
POST_USERNAME = str(request.form['email'])
POST_PASSWORD = str(request.form['password'])
# Session = sessionmaker(bind=engine)
# s = db.session
query = User.query.filter(User.email==POST_USERNAME,
User.password==POST_PASSWORD)
result = query.first()
if result.active == False:
flash ('Account not yet active, please wait for admin')
return render_template('login.html')
elif result:
session['logged_in'] = True
flash('SUCCESS: Logged In!')
data_dict = dict(username=POST_USERNAME)
else:
flash('wrong password!')
return render_template('login.html')
return render_template('index.html',**data_dict)
return render_template('login.html')
# Logging Out
@app.route('/logout')
def logout():
session['logged_in'] = False
flash('SUCCESS: Logged Out!')
return index()
# Signing Up
@app.route('/showSignUp', methods =['GET'])
def showSignUp():
global resultnum
firstnum = int(random.random() * 10)
secondnum = int(random.random() * 10)
resultnum = firstnum + secondnum
return render_template('signup.html', firstnum = firstnum, secondnum = secondnum, resultnum = resultnum)
# Success Message
@app.route('/success', methods =['GET', 'POST'])
def success():
global resultnum
if request.method == 'POST' and int(request.form['captcha']) == int(resultnum):
firstname = request.form['inputFirstName']
lastname = request.form['inputLastName']
email = request.form['inputEmail']
password = request.form['inputPassword']
phone = request.form['phoneNumber']
if not db.session.query(User).filter(User.email == email).count():
entry = User(email, password, firstname, lastname, phone)
db.session.add(entry)
db.session.commit()
return render_template('success.html')
return render_template('success.html')
@app.route('/posted', methods = ['GET', 'POST'])
def posted():
if request.method == 'POST':
title = request.form['title']
price = request.form['price']
descr = request.form['descr']
entry = Post(1,title, price, descr)
db.session.add(entry)
db.session.commit()
return render_template('success.html')
return render_template('success.html')
if (__name__)=='__main__':
app.run(host='localhost', port=5000, debug=True)
# User profile pages accessible by /user/id
@app.route('/user/<id>')
#@login_required
def user(id):
user = User.query.filter_by(id=id).first()
return render_template('user_profile.html', user=user)
#Rendering pages for testing purposes delete when finished
@app.route('/post')
def post():
return render_template('post.html')
@app.route('/item/<id>')
def item(id):
item = Post.query.filter_by(id=id).first()
return render_template('item.html', item=item)
@app.route('/showPosts')
def show_entries():
entries = Post.query.order_by(Post.userid)
return render_template('show_entries.html', entries = entries)
'''
sample code from flaskr.app tutorial
#main page
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries = entries)
#my code
allpost = Post.query.filter_by(id).first()
return render_template('show_entries.html', allpost = allpost)
#joseph's code
@app.route('/add', methods=['POST'])
def posting():
#adding entries
if not session.get('logged_in'):
print("not session.get('logged_in')")
abort(401)
db = get_db()
db.execute('insert into entries (title, text) values (?,?)',
[request.form['title'], request.form['text']])
db.commit()
flash('New entry was sucessfully posted')
return redirect(url_for('show_entries'))
'''