-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
206 lines (180 loc) · 6.01 KB
/
__init__.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
#-*- coding: utf-8 -*-
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect, url_for
from flask import session
# -*- coding: iso-8859-15 -
from flask_cors import CORS, cross_origin
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_session import Session
import os
import json
import hashlib
app = Flask(__name__)
app.config.from_pyfile('utils/config.py')
app.secret_key = "dafuq?lolasso"
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from utils import models
# db.create_all()
# cors = CORS(app)
# app.config['CORS_HEADERS'] = 'Content-Type'
@app.route('/')
def web():
imgs = models.Img.query.all()[::-1]
# Separate images by sets of 3
data, aux = [], []
for img in imgs[5:]:
aux.append(img)
if len(aux) == 3:
data.append(aux)
aux = []
if len(aux)>0: data.append(aux)
return render_template('index.html', data=data, imgs=imgs[:5])
@app.route('/demo/')
def demo():
return render_template('safe_index.html')
@app.route('/post<id>/')
def post(id):
image = models.Img.query.filter_by(id=id).first()
# retrieve comments and sort by popularity
comments = models.Comment.query.filter_by(img_id=id)
comments = [x for x in sorted(comments, key=lambda x: x.score, reverse=True)]
return render_template('post.html', image=image, comments=comments)
@app.route('/last/')
def last():
img = models.Img.query.all()[-1]
return redirect('/post'+str(img.id)+'/')
@app.route('/add_comment/', methods=['POST'])
def add_comment():
username = session["username"]
text = request.form['text']
img_id = request.form['img_id']
score = 0
voters = ""
comment = models.Comment(username, text, img_id, score, voters)
db.session.add(comment)
db.session.commit()
return redirect('/post'+img_id+'/')
@app.route('/<img_id>upvote<id>/')
def upvote(img_id, id):
#Check if session is active
if session.get("username"):
comment = models.Comment.query.filter_by(id=id).first()
if session["username"] not in comment.voters.split(" "):
comment.score += 1
comment.voters += session["username"]+" "
db.session.merge(comment)
db.session.commit()
return redirect('/post'+img_id+'/')
# Don't allow voting if not logged in
else:
return redirect(url_for("login"))
@app.route('/leaderboard/')
def leader():
data = []
users = models.User.query.all()
comments = models.Comment.query.all()
for user in users:
score = 0
for comment in comments:
if user.username == comment.username:
score += comment.score
data.append({"username": user.username, "score":score})
data = [x for x in sorted(data, key=lambda x: x["score"], reverse=True)]
for i in range(len(data)):
data[i]["pos"] = i+1
return render_template('leader.html', data=data)
@app.route('/signup/')
def signup():
return render_template('signup.html', mess=None)
@app.route('/login/')
def login():
return render_template('login.html')
@app.route('/logger/', methods = ['GET', 'POST'])
def logger():
email = request.form['email']
password = hashlib.sha256(bytearray(request.form['password'], "utf-8")).hexdigest()
# Check if user is registered in db
in_db = models.User.query.filter_by(email=email, password=password).first()
if in_db: # if user_in_db: update session values
username = in_db.username
user_id = in_db.id
session["username"] = username
session["email"] = email
session["id"] = user_id
return redirect(url_for('web'))
else:
return render_template('login.html', mess="Email or password are incorrect")
@app.route('/logout/')
def logout():
# remove the username, id from the session if it is there
if session.get("username"):
session.pop('username', None)
session.pop('id', None)
session.pop('email', None)
return redirect(url_for('web'))
@app.route('/new_user/', methods = ['GET', 'POST'])
def new_user():
# if not all fields complete, don't allow sign up
if request.form['username'] == "" or request.form['email'] == "" or request.form['password'] == "":
return render_template('signup.html', mess="Fill all the items please")
username = request.form['username']
email = request.form['email']
password = hashlib.sha256(bytearray(request.form['password'], "utf-8")).hexdigest()
re_password = hashlib.sha256(bytearray(request.form['re_password'], "utf-8")).hexdigest()
# Check if username/email is already in db
name_in_db = models.User.query.filter_by(username=username).first()
email_in_db = models.User.query.filter_by(email=email).first()
if name_in_db or email_in_db: # if user_in_db: update session values
return render_template('signup.html', mess="Email or username are already registered")
# Check if passwords don't match
elif password != re_password:
return render_template('signup.html', mess="Passwords don't match")
# If everything is correct, add user to DB and redirect to login
else:
user = models.User(username, email, password)
db.session.add(user)
db.session.commit()
return render_template('login.html', mess="Signed up successfully")
@app.route('/testing/')
def testing():
# Check users working correctly
sols = []
q = models.User.query.all()
db.session.commit()
for line in q:
sols.append({"id": str(line.id),
"name": str(line.username),
"email": str(line.email),
"password": str(line.password)})
# Check comments working correctly
comms = []
q = models.Comment.query.all()
db.session.commit()
for line in q:
comms.append({"id": str(line.id),
"name": str(line.username),
"text": str(line.text),
"img_id": str(line.img_id),
"score": str(line.score),
"voters": str(line.voters)})
# Check images working correctly
imgs = []
q = models.Img.query.all()
db.session.commit()
for line in q:
imgs.append({"id": str(line.id),
"name": str(line.name),
"source_name": str(line.source_name),
"source_link": "https://"+str(line.source_link)})
return str(sols)+"\n \n"+str(comms)+"\n \n"+str(imgs)
if __name__ == '__main__':
# # Deploying
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
# Debugging
# app.run(debug=True, host='0.0.0.0')