/
routes.py
214 lines (185 loc) · 8.54 KB
/
routes.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
import random
from BinTree import BinTree
import flask
import flask_login
import forms
import db
app = flask.Flask(__name__)
app.config.from_object('config')
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(flask_login.UserMixin):
def __init__(self, username, primary_id, difficulty, active=True):
self.username = username
self.primary_id = primary_id
self.difficulty = difficulty
self.active = active
def get_id(self):
return str(self.primary_id).encode().decode()
def is_active(self):
return self.active
@login_manager.user_loader
def load_user(user_id):
try:
with db.create_connection() as connection, connection.cursor() as cursor:
sql = "SELECT * FROM users WHERE id=%s"
cursor.execute(sql, (user_id))
result = cursor.fetchone()
if result:
return User(result['username'], result['id'], result['difficulty'])
return None
except:
return None
def generate_statement_string(sections, rand_min=-100, rand_max=100):
statement_str = ''
while sections > 0:
statement_str += ' '.join([random.choice(['x', 'y', str(random.randint(rand_min, rand_max))]),
random.choice(['>', '<', '==', '!=', '>=', '<=']),
random.choice(['x', 'y', str(random.randint(rand_min, rand_max))])])
if sections == 1:
return statement_str
statement_str += ' ' + random.choice(['||', '&&']) + ' '
sections -= 1
@app.route('/', methods=['GET', 'POST'])
def home():
x = random.randint(-100, 100)
y = random.randint(-100, 100)
if flask_login.current_user.is_anonymous:
statement_str = generate_statement_string(2)
else:
statement_str = generate_statement_string(flask_login.current_user.difficulty)
tree = BinTree.build_tree(statement_str)
statement_result = BinTree.solve_tree(tree, x, y)
form = forms.TrueOrFalseForm(flask.request.form)
if form.validate_on_submit():
if not flask_login.current_user.is_anonymous:
difficulty = flask_login.current_user.difficulty
if form.choice.data == form.hidden.data:
with db.create_connection() as connection, connection.cursor() as cursor:
sql = "UPDATE users SET score = score + %s WHERE id = %s"
cursor.execute(sql, (difficulty, flask_login.current_user.primary_id))
connection.commit()
flask.flash('Correct! +{0} points!'.format(difficulty), 'success')
else:
with db.create_connection() as connection, connection.cursor() as cursor:
sql = "UPDATE users SET score = score - %s WHERE id = %s"
cursor.execute(sql, (difficulty / 2, flask_login.current_user.primary_id))
connection.commit()
flask.flash('Incorrect! -{0} points!'.format(difficulty / 2), 'error')
else:
if form.choice.data == form.hidden.data:
flask.flash('Correct!', 'success')
else:
flask.flash('Incorrect!', 'error')
elif form.errors:
for item in form.errors.items():
flask.flash(item, 'error')
return flask.render_template('home.html', x_value=str(x), y_value=str(y), statement=statement_str,
result=str(statement_result), form=form)
@app.route('/tester', methods=['GET', 'POST'])
def tester():
form = forms.StatementForm()
if form.validate_on_submit():
try:
solution = BinTree.solve_tree(BinTree.build_tree(form.statement.data), 0, 0)
if type(solution) is not bool:
raise ValueError
flask.flash('Given statement is {0}, solution is {1}'.format(form.statement.data, str(solution)))
except (ValueError, IndexError):
flask.flash('Invalid statement!', 'error')
elif form.errors:
for item in form.errors.items():
flask.flash(item, 'error')
return flask.render_template('tester.html', form=form)
@app.route('/login', methods=['GET', 'POST'])
def login():
if not flask_login.current_user.is_anonymous:
flask.flash('Already logged in!', 'error')
return flask.redirect('/')
login_form = forms.LoginForm(prefix='login_form')
signup_form = forms.SignupForm(prefix='signup_form')
if signup_form.register.data and signup_form.validate_on_submit():
with db.create_connection() as connection:
with connection.cursor() as cursor:
sql = "SELECT * FROM users WHERE username=%s OR email=%s"
cursor.execute(sql, (signup_form.username.data, signup_form.email.data))
result = cursor.fetchone()
if result:
flask.flash('Username or email already exist!', 'error')
return flask.redirect('/login')
with connection.cursor() as cursor:
sql = "INSERT INTO users (username, email, password) VALUES (%s, %s, SHA2(%s, 256))"
cursor.execute(sql, (signup_form.username.data, signup_form.email.data, signup_form.password.data))
connection.commit()
with db.create_connection() as connection, connection.cursor() as cursor:
sql = "SELECT * FROM users WHERE username=%s AND password=SHA2(%s, 256)"
cursor.execute(sql, (signup_form.username.data, signup_form.password.data))
result = cursor.fetchone()
if flask_login.login_user(load_user(result['id'])):
flask.flash('User created and logged in!', 'success')
return flask.redirect('/')
else:
flask.flash('User created but not logged in.')
elif signup_form.errors:
for item in signup_form.errors.items():
flask.flash(item, 'error')
if login_form.login.data and login_form.validate_on_submit():
with db.create_connection() as connection, connection.cursor() as cursor:
sql = "SELECT * FROM users WHERE username=%s AND password=SHA2(%s, 256)"
cursor.execute(sql, (login_form.username.data, login_form.password.data))
result = cursor.fetchone()
if result:
if flask_login.login_user(load_user(result['id']), remember=login_form.remember_me.data):
flask.flash('Logged in!', 'success')
return flask.redirect('/')
else:
flask.flash('Sorry, something went wrong.', 'error')
else:
flask.flash('Invalid username or password.', 'error')
elif login_form.errors:
for item in login_form.errors.items():
flask.flash(item, 'error')
return flask.render_template('login.html', login_form=login_form, signup_form=signup_form)
@app.route('/about')
def about():
return flask.render_template('about.html')
@app.route('/user/<name>')
def profile(name):
with db.create_connection() as connection, connection.cursor() as cursor:
sql = "SELECT * FROM users WHERE username=%s"
cursor.execute(sql, (name))
result = cursor.fetchone()
if not result:
flask.flash('No such user!')
return flask.redirect('/')
return flask.render_template('profile.html', score=result['score'], username=name)
@app.route('/leaderboard')
def leaderboard():
with db.create_connection() as connection, connection.cursor() as cursor:
sql = "SELECT * FROM users ORDER BY score DESC"
cursor.execute(sql)
user_dict = cursor.fetchall()
return flask.render_template('leaderboard.html', user_dict=user_dict)
@app.route('/dashboard', methods=['GET', 'POST'])
@flask_login.login_required
def dashboard():
form = forms.DifficultyForm()
if form.validate_on_submit():
with db.create_connection() as connection, connection.cursor() as cursor:
sql = "UPDATE users SET difficulty = %s WHERE id = %s"
cursor.execute(sql, (form.difficulty.data, flask_login.current_user.primary_id))
connection.commit()
flask.flash("Difficulty updated! Good luck!", 'success')
return flask.redirect('/')
elif form.errors:
flask.flash(form.errors, 'error')
return flask.render_template('dashboard.html', form=form)
@app.route('/logout')
@flask_login.login_required
def logout():
flask_login.logout_user()
flask.flash('Logged out.')
return flask.redirect('/')
if __name__ == '__main__':
app.run(debug=True)