-
Notifications
You must be signed in to change notification settings - Fork 0
/
sigame_api.py
271 lines (246 loc) · 12.2 KB
/
sigame_api.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
from flask import Flask
from flask import render_template, redirect, request, abort
from data import db_session
from flask_login import LoginManager
from data.users import User
from data.packs import Pack
from data.packs_resources import PackResource
from data.forms import LoginForm, RegisterForm, GameForm
from flask_login import login_user, logout_user, login_required, current_user
from flask_restful import Api
import os
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = 'yandexlyceum_secret_key'
login_manager = LoginManager()
login_manager.init_app(app)
# создание приложения
api = Api(app)
api.add_resource(PackResource, '/api/v2/packs/<int:pack_id>')
# создание API
@app.route("/")
def index():
session = db_session.create_session()
game_id = session.query(Pack).filter(Pack.id).all()[-1].id + 1
return render_template('base.html', game_id=game_id)
# стартовая страница
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
session = db_session.create_session()
user = session.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("/")
return render_template('login.html',
message="Incorrect Login or Password",
form=form)
return render_template('login.html', title='Authorization', form=form)
# страница входа
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect("/")
# выход из профиля
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
if form.password.data != form.password_again.data:
return render_template('register.html', title='Registration',
form=form,
message="Passwords don't match")
session = db_session.create_session()
if session.query(User).filter(User.email == form.email.data).first():
return render_template('register.html', title='Registration',
form=form,
message="User already exists")
user = User(
email=form.email.data,
surname=form.surname.data,
name=form.name.data,
about=form.about.data
)
user.set_password(form.password.data)
session.add(user)
session.commit()
return redirect('/login')
return render_template('register.html', title='Registration', form=form)
# страница регистрации
@app.route('/game/<int:game_id>/rounds/<int:round>/category', methods=['GET', 'POST'])
def game(game_id, round):
session = db_session.create_session()
game_form = GameForm()
if game_form.validate_on_submit() and game_form.category_submit.data: # если нажата кнопка добавления категории
if not session.query(Pack).filter((Pack.id == game_id)).first():
with open(f'games/{game_id}.json', 'w') as f:
data = {
"rounds": [
{
"categories": [
]
}
]
}
json.dump(data, f, indent=4)
pack = Pack(
game=f'games/{game_id}.json',
user_id=current_user.id
) # в таблицу записывается путь к файлу и id создателя
session.add(pack)
session.commit()
category_data = ({
"name": game_form.category.data,
"description": game_form.description.data,
"questions": [
{
"text": game_form.text.data,
"par": game_form.par.data,
"correct_answers": game_form.answers.data,
"answer_time": game_form.time.data
},
{
"text": game_form.text_1.data,
"par": game_form.par_1.data,
"correct_answers": game_form.answers_1.data,
"answer_time": game_form.time_1.data
},
{
"text": game_form.text_2.data,
"par": game_form.par_2.data,
"correct_answers": game_form.answers_2.data,
"answer_time": game_form.time_2.data
},
{
"text": game_form.text_3.data,
"par": game_form.par_3.data,
"correct_answers": game_form.answers_3.data,
"answer_time": game_form.time_3.data
},
{
"text": game_form.text_4.data,
"par": game_form.par_4.data,
"correct_answers": game_form.answers_4.data,
"answer_time": game_form.time_4.data
}
]
},)
with open(f'games/{game_id}.json') as f:
data = json.load(f)
data["rounds"][round - 1]["categories"] += list(category_data)
with open(f'games/{game_id}.json', 'w') as f:
json.dump(data, f, indent=4)
return redirect(
f'/game/{game_id}/rounds/{round}/category') # перенаправление на эту же страницу для добавления категории
elif game_form.validate_on_submit() and game_form.round_submit.data: # если нажата кнопка перехода к следующему раунду
round_data = ({
"categories": [
]
},)
with open(f'games/{game_id}.json') as f:
data = json.load(f)
data["rounds"] += list(round_data)
with open(f'games/{game_id}.json', 'w') as f:
json.dump(data, f, indent=4)
category_data = ({
"name": game_form.category.data,
"description": game_form.description.data,
"questions": [
{
"text": game_form.text.data,
"par": game_form.par.data,
"correct_answers": game_form.answers.data,
"answer_time": game_form.time.data
},
{
"text": game_form.text_1.data,
"par": game_form.par_1.data,
"correct_answers": game_form.answers_1.data,
"answer_time": game_form.time_1.data
},
{
"text": game_form.text_2.data,
"par": game_form.par_2.data,
"correct_answers": game_form.answers_2.data,
"answer_time": game_form.time_2.data
},
{
"text": game_form.text_3.data,
"par": game_form.par_3.data,
"correct_answers": game_form.answers_3.data,
"answer_time": game_form.time_3.data
},
{
"text": game_form.text_4.data,
"par": game_form.par_4.data,
"correct_answers": game_form.answers_4.data,
"answer_time": game_form.time_4.data
}
]
},)
with open(f'games/{game_id}.json') as f:
data = json.load(f)
data["rounds"][round - 1]["categories"] += list(category_data)
with open(f'games/{game_id}.json', 'w') as f:
json.dump(data, f, indent=4)
return redirect(
f'/game/{game_id}/rounds/{round + 1}/category') # перенаправление на страницу оформления категории для следующего раунда
elif game_form.validate_on_submit() and game_form.finish_submit.data: # если нажата кнопка окончания создания пака
category_data = ({
"name": game_form.category.data,
"description": game_form.description.data,
"questions": [
{
"text": game_form.text.data,
"par": game_form.par.data,
"correct_answers": game_form.answers.data,
"answer_time": game_form.time.data
},
{
"text": game_form.text_1.data,
"par": game_form.par_1.data,
"correct_answers": game_form.answers_1.data,
"answer_time": game_form.time_1.data
},
{
"text": game_form.text_2.data,
"par": game_form.par_2.data,
"correct_answers": game_form.answers_2.data,
"answer_time": game_form.time_2.data
},
{
"text": game_form.text_3.data,
"par": game_form.par_3.data,
"correct_answers": game_form.answers_3.data,
"answer_time": game_form.time_3.data
},
{
"text": game_form.text_4.data,
"par": game_form.par_4.data,
"correct_answers": game_form.answers_4.data,
"answer_time": game_form.time_4.data
}
]
},)
with open(f'games/{game_id}.json', encoding='utf-8') as f:
data = json.load(f)
data["rounds"][round - 1]["categories"] += list(category_data)
with open(f'games/{game_id}.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4)
return redirect('/') # возврат на главную
elif request.method == 'GET':
return render_template('game.html', title='Game editing', game_form=game_form)
@login_manager.user_loader
def load_user(user_id):
session = db_session.create_session()
return session.query(User).get(user_id)
# получение пользователя
def main():
db_session.global_init("db/si_game.sqlite")
port = int(os.environ.get("PORT", 10000))
app.run(host='10.128.0.16', port=port)
# запуск приложения
if __name__ == '__main__':
main()