-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
239 lines (205 loc) · 8.64 KB
/
main.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
from flask_login import login_user, LoginManager, login_manager, login_required, logout_user, current_user, mixins
from data.Game import Game
from data.EGSGameData import EGSGameData
from data.SteamGameData import SteamGameData
from data.db_session import *
from data.users import User, EditForm, RegisterForm, LoginForm
import flask
from flask import Flask, render_template, redirect, request, url_for, flash, make_response
from os.path import dirname, join
from flask_caching import Cache
from json import loads
app = Flask(__name__, static_folder=join(dirname(__file__), 'static'))
app.config['SECRET_KEY'] = 'hello'
cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 60})
cache.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_message = 'Авторизуйтесь для доступа к закрытым страницам'
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
if flask.request.method == 'POST':
cache.set('name', flask.request.form.get('game_name'))
return redirect('/games')
return render_template('index.html')
@app.route('/games', methods=['GET', 'POST'])
@app.route('/games/<int:page>', methods=['GET', 'POST'])
def games(page=1):
last_page = first_page = False
query = db_sess.query(Game)
if flask.request.method == 'POST':
cache.set('name', flask.request.form.get('name'))
if flask.request.form.get('price') == 'up':
cache.set('price_up', True)
else:
cache.set('price_up', False)
return redirect('/games')
if cache.get('name'):
name = cache.get('name')
query = query.filter(Game.name.like(f'%{name}%'))
len_games_list = query.count()
if page <= 0:
return redirect('/games')
elif page > len_games_list // 15 + 1:
page = len_games_list // 15 + 1
return redirect(f'/games/{page}')
if page == 1:
first_page = True
if page == len_games_list // 15 + 1 and len_games_list % 15 > 0\
or page == len_games_list // 15 and len_games_list % 15 == 0:
last_page = True
if cache.get('price_up'):
games_list = list(query.order_by(Game.min_price).limit(15).offset(15 * (page - 1)))
else:
games_list = list(query.order_by(-Game.min_price).limit(15).offset(15 * (page - 1)))
return render_template('games.html', games=games_list, price_up=cache.get('price_up'), name=cache.get('name'),
page=page, first_page=first_page, last_page=last_page)
@app.route('/game/<int:game_id>')
def game(game_id: int):
game = db_sess.query(Game).filter(Game.id == game_id).first()
imgs = dlcs = metacritic = None
if game:
if game.steam_game:
if game.steam_game.screenshots:
imgs = loads(game.steam_game.screenshots)
if game.steam_game.dlc:
dlcs = game.steam_game.dlc
if game.steam_game.metacritic:
metacritic = loads(game.steam_game.metacritic)
return render_template('game.html', game=game, dlcs=dlcs, imgs=imgs, metacritic=metacritic)
return f'Game with id {game_id} doesn`t exists'
@login_required
@app.route('/follow/<int:id>', methods=['GET', 'POST'])
def follow(id):
if current_user.is_authenticated:
print(id)
if current_user.foll_games:
foll_games = current_user.foll_games.split()
else:
foll_games = []
print(foll_games)
if foll_games and str(id) not in foll_games:
current_user.foll_games = f'{current_user.foll_games}, {id}'
elif str(id) in foll_games:
flash('You are already following this game')
else:
current_user.foll_games = f'{id}'
game = db_sess.query(Game).filter(Game.id == id).first()
if game.foll_profiles:
profiles = game.foll_profiles.split()
else:
profiles = []
if profiles and str(current_user.id) not in profiles:
game.foll_profiles = f'{game.foll_profiles}, {current_user.id}'
else:
game.foll_profiles = f'{current_user.id}'
db_sess.merge(current_user)
db_sess.commit()
return redirect(url_for('games'))
return redirect('/register')
@login_required
@app.route('/unfollow/<int:id>', methods=['GET', 'POST'])
def unfollow(id):
if current_user.is_authenticated:
foll_games = current_user.foll_games.split(', ')
foll_games.remove(str(id))
foll_games = ', '.join(foll_games)
current_user.foll_games = foll_games
game = db_sess.query(Game).filter(Game.id == id).first()
profiles = game.foll_profiles.split(', ')
profiles.remove(str(current_user.id))
game.foll_profiles = ', '.join(profiles)
db_sess.merge(current_user)
db_sess.commit()
return redirect(url_for('profile'))
return redirect('/register')
@login_manager.user_loader
def load_user(user_id):
return db_sess.query(User).get(user_id)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect("/")
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = db_sess.query(User).filter(User.email == form.email.data).first()
if user and user.check_password(form.password.data):
login_user(user, remember=form.remember_me.data)
return redirect(url_for('index'))
return render_template('login.html',
message="Неправильный логин или пароль",
form=form)
return render_template('login.html', title='Авторизация', form=form)
@app.route('/register', methods=['GET', 'POST'])
def reqister():
form = RegisterForm()
if form.validate_on_submit():
if form.password.data != form.password_again.data:
return render_template('register.html', title='Регистрация',
form=form,
message="Пароли не совпадают")
if db_sess.query(User).filter(User.email == form.email.data).first():
return render_template('register.html', title='Регистрация',
form=form,
message="Такой пользователь уже есть")
user = User(
name=form.name.data,
email=form.email.data,
age=form.age.data,
profile_photo=open('static/img/no_avatar.png', 'rb').read()
)
user.set_password(form.password.data)
db_sess.add(user)
db_sess.commit()
return redirect(url_for('login'))
return render_template('register.html', title='Регистрация', form=form)
@login_required
@app.route('/profile_edit', methods=['GET', 'POST'])
def profile_edit():
form = EditForm()
if request.method == "GET":
form.email.data = current_user.email
form.name.data = current_user.name
if form.validate_on_submit():
if current_user.check_password(form.old_password.data) or form.new_password.data == '':
f = form.avatar.data
current_user.name = form.name.data
current_user.email = form.email.data
current_user.age = form.age.data
current_user.password = form.new_password.data
current_user.profile_photo = f.read()
db_sess.merge(current_user)
db_sess.commit()
return redirect(url_for('profile'))
flash('Неправильный пароль')
return render_template('profile_edit.html', title='Edit Profile', form=form)
return render_template('profile_edit.html', title='Edit Profile', form=form)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html')
@app.route('/user_avatar/id<int:id>')
@login_required
def user_avatar(id):
img = db_sess.query(User).filter(User.id == id).first().profile_photo
if not img:
return ""
h = make_response(img)
return h
@login_required
@app.route('/profile', methods=['GET', 'POST'])
def profile():
if current_user.foll_games:
foll_games = current_user.foll_games.split(', ')
foll_games = list(map(lambda x: int(x), foll_games))
games_list = db_sess.query(Game).filter(Game.id.in_(foll_games)).all()
else:
games_list = []
return render_template('profile.html', title='Profile', games=games_list)
if __name__ == '__main__':
global_init('db/games.db')
db_sess = create_session()
app.run(port=8080, host='127.0.0.1')