-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
573 lines (522 loc) · 24.3 KB
/
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
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
import json
import logging
import time
import sys
import os
from flask import Flask
from flask import request as frequest
from flask_restful import Api, Resource
from config.config import HOST, PORT
from app import db_worker
########################################################################################################################
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
stream=sys.stdout,
format='[%(asctime)s]:[%(levelname)s]:[%(filename)s]:[%(lineno)d]: %(message)s',
)
########################################################################################################################
class LengthError(TypeError):
"""
It called when the length of the data is not within the constraints
"""
class AccessError(TypeError):
"""
It called when the user tries to access objects that do not belong to him.
"""
########################################################################################################################
class Words(Resource): # Resource - restfull king
"""
Words database query handler class
"""
def get(self, token):
"""
Outputs all user words data
:param token: string user token from db table apikeys
"""
try:
db_worker.pending_rollback(token)
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] GET WORDS')
try:
data_path = db_worker.create_file_with_user_words(
user_tg_id=str(sql_user.tg_id),
file_path='temporary',
file_type='json',
sql_filter_key='default',
sql_sort_key='all my words',
)
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t made data file "{e}"')
return {'error': 'Failed to collect words from data base for query'}, 500
else:
logger.info(f'[{sql_user.nickname}] WORDS DATA IN "{data_path}"')
try:
file = open(data_path, 'r', encoding='utf-8')
data = json.load(file)
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t load json file "{e}"')
return {'error': 'Failed to collect words from temporary file for query'}, 500
else:
file.close()
os.remove(data_path)
logger.info(f'[{sql_user.nickname}] SUCCESS GET WORDS')
return data, 200
class Lesson(Resource):
"""
Lesson query handler class
"""
def get(self, token):
"""
Forms and outputs the jsonyfy lesson
:param token: string user token from db table apikeys
"""
try:
db_worker.pending_rollback(token)
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] GET LESSON')
try:
data = db_worker.get_lesson_data(tg_id=sql_user.tg_id)
except db_worker.MinLenError as e:
logger.error(f'[{sql_user.nickname}] Can`t make data file "{e}"')
return {'error': f'Not enough words for lesson. You have {e}, minimum 15'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t make data file "{e}"')
return {'error': 'Failed to collect lesson from data base for query'}, 500
else:
logger.info(f'[{sql_user.nickname}] LESSON DATA ({len(data)})')
logger.info(f'[{sql_user.nickname}] SUCCESS GET LESSON')
return data, 200
class Example(Resource):
"""
Example database query handler class
"""
def get(self, token, example_id):
"""
Returns example json data
:param token: string user token from db table apikeys
:param example_id: integer example id from db examples
"""
try:
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] GET EXAMPLE')
try:
sql_example = db_worker.get_example(example_id)
if not sql_example.user_id == sql_user.user_id:
raise AccessError
except AccessError as e:
logger.error(f'[{sql_user.nickname}] Can`t get data. Access denied "{e}"')
return {'error': f'A user with such a token does not have access rights to an example with this id'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data "{e}"')
return {'error': 'Failed to process your example object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] EXAMPLE IS READY TO BE RETURNED')
try:
returned_data = {
'ex_id': sql_example.ex_id,
'example': sql_example.example,
'user_id': sql_example.user_id
}
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data from sql "{e}"')
return {'error': 'Failed to process your example object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] SUCCESS GET EXAMPLE')
return returned_data, 200
def post(self, token, example_id):
"""
Posts example in examples db by json user data
:param token: string user token from db table apikeys
:body form-data: {'example': '<your_example>'}
"""
try:
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] POST EXAMPLE')
try:
new_example_data = frequest.form.to_dict()
example = new_example_data['example']
example_len = len(example)
if example_len > 400 or example_len < 5:
raise LengthError(f"{example_len}")
except LengthError as e:
logger.error(f'[{sql_user.nickname}] Can`t write data. Wrong length "{e}"')
return {'error': f'Not right length for example. You have {e}, min 5 - max 400'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data "{e}"')
return {'error': 'Failed to process your example object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] EXAMPLE IS READY TO BE RECORDED')
try:
sql_example = db_worker.add_example(
example_text=example,
user_tg_id=sql_user.tg_id
)
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data to sql "{e}"')
return {'error': 'Failed to process your example object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] SUCCESS POST EXAMPLE')
return {
'ex_id': sql_example.ex_id,
'example': sql_example.example,
'user_id': sql_example.user_id
}, 200
def put(self, token, example_id):
"""
Puts example in examples db by json user data
:param token: string user token from db table apikeys
:form-data: {'example': '<your_example>'}
"""
try:
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] PUT EXAMPLE')
try:
sql_example = db_worker.get_example(example_id=example_id)
new_example_data = frequest.form.to_dict()
example = new_example_data['example']
example_len = len(example)
if example_len > 400 or example_len < 5:
raise LengthError(f"{example_len}")
if not sql_example.user_id == sql_user.user_id:
raise AccessError
except LengthError as e:
logger.error(f'[{sql_user.nickname}] Can`t write data. Wrong length "{e}"')
return {'error': f'Not right length for example. You have {e}, min 5 - max 400'}, 404
except AccessError as e:
logger.error(f'[{sql_user.nickname}] Can`t get data. Access denied "{e}"')
return {'error': f'A user with such a token does not have access rights to an example with this id'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data "{e}"')
return {'error': 'Failed to process your example object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] EXAMPLE IS READY TO BE EDIT')
try:
db_worker.update_data(
data_type='example',
data_id=sql_example.ex_id,
new_data=example
)
sql_example = db_worker.get_example(
example_id=sql_example.ex_id
)
returned_data = {
'ex_id': sql_example.ex_id,
'example': sql_example.example,
'user_id': sql_example.user_id
}
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data from sql "{e}"')
return {'error': 'Failed to process your example object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] SUCCESS PUT EXAMPLE')
return returned_data, 200
def delete(self, token, example_id):
"""
Deletes example in examples db by int example id
:param token: string user token from db table apikeys
:form-data: {'example': '<your_example>'}
"""
try:
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] DELETE EXAMPLE')
try:
sql_example = db_worker.get_example(example_id=example_id)
if not sql_example.user_id == sql_user.user_id:
raise AccessError
except AccessError as e:
logger.error(f'[{sql_user.nickname}] Can`t delete data. Access denied "{e}"')
return {'error': f'A user with such a token does not have access rights to an example with this id'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data "{e}"')
return {'error': 'Failed to process your example object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] EXAMPLE IS READY TO BE DELETED')
try:
db_worker.delete_data(
data_type='example',
data_id=example_id
)
sql_example = db_worker.get_example(example_id)
returned_data = {
'success': 'Your data has been successfully deleted'
}
if sql_example:
raise RuntimeError('Data was not successfully deleted from sql table')
except RuntimeError as e:
logger.error(f'[{sql_user.nickname}] Can`t delete data from sql "{e}"')
return {'error': 'Data was not successfully deleted from table, problem on our end, please try again'}, 500
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t delete data from sql "{e}"')
return {'error': 'Failed to process your example object - check the correctness of the data id'}, 404
else:
logger.info(f'[{sql_user.nickname}] SUCCESS DELETE EXAMPLE')
return returned_data, 200
class Word(Resource):
"""
Word database query handler class
"""
def get(self, token, word_id):
"""
Returns word json data
:param token: string user token from db table apikeys
:param word_id: integer word id from db words
"""
try:
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] GET WORD')
try:
sql_word = db_worker.get_word(word_id)
sql_example = db_worker.get_example(sql_word.example_id)
if not sql_example.user_id == sql_user.user_id:
raise AccessError
except AccessError as e:
logger.error(f'[{sql_user.nickname}] Can`t get data. Access denied "{e}"')
return {'error': f'A user with such a token does not have access rights to an word with this id'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data "{e}"')
return {'error': 'Failed to process your word object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] WORD IS READY TO BE RETURNED')
try:
returned_data = {
'word_id': sql_word.word_id,
'word': sql_word.word,
'description': sql_word.description,
'example_id': sql_word.example_id
}
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data from sql "{e}"')
return {'error': 'Failed to process your word object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] SUCCESS GET WORD')
return returned_data, 200
def post(self, token, word_id):
"""
Posts word from json data
:param token: string user token from db table apikeys
"""
try:
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] POST WORD')
try:
new_word_data = frequest.form.to_dict()
word = new_word_data['word']
word_len = len(word)
description = new_word_data['description']
description_len = len(description)
example_id = int(new_word_data['ex_id'])
sql_example = db_worker.get_example(example_id)
if not sql_example.user_id == sql_user.user_id:
raise AccessError(f'Data owner: {sql_example.user_id}, Query owner: {sql_user.user_id}')
if word_len > 135 or word_len < 1:
raise LengthError(f"{word_len}")
if description_len > 400 or description_len < 1:
raise LengthError(f"{description_len}")
except LengthError as e:
logger.error(f'[{sql_user.nickname}] Can`t write data. Wrong length "{e}"')
return {'error': f'Not right length for word or description. You have {e},'
f' min 1 - max 135(word) | max 400(description)'}, 404
except AccessError as e:
logger.error(f'[{sql_user.nickname}] Can`t write data. Access denied "{e}"')
return {'error': f'A user with such a token does not have access rights to an example with this id'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data "{e}"')
return {'error': 'Failed to process your word object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] WORD IS READY TO BE RECORDED')
try:
sql_word = db_worker.add_word(
word=word,
description=description,
category=db_worker.get_word_category(word),
rating=0,
example=sql_example
)
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data to sql "{e}"')
return {'error': 'There was a problem on our side, please try again later'}, 500
else:
logger.info(f'[{sql_user.nickname}] SUCCESS POST WORD')
return {
'word_id': sql_word.word_id,
'word': sql_word.word,
'description': sql_word.description,
'example_id': sql_word.example_id
}, 200
def put(self, token, word_id):
"""
Puts word from json data
:param token: string user token from db table apikeys
:param word_id: integer word id from db words
"""
try:
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] PUT WORD')
flag = 'word or description'
try:
sql_word = db_worker.get_word(word_id=word_id)
sql_example = db_worker.get_example(example_id=int(sql_word.example_id))
new_word_data = frequest.form.to_dict()
word = new_word_data['word']
word_len = len(word)
description = new_word_data['description']
description_len = len(description)
if not sql_example.user_id == sql_user.user_id:
raise AccessError(f'Data owner: {sql_example.user_id}, Query owner: {sql_user.user_id}')
if word_len > 135 or word_len < 1:
flag = 'word'
raise LengthError(f"{word_len}")
if description_len > 400 or description_len < 1:
flag = 'description'
raise LengthError(f"{description_len}")
except LengthError as e:
logger.error(f'[{sql_user.nickname}] Can`t write data. Wrong length "{e}"')
return {'error': f'Not right length for {flag}. You have {e},'
f' min 1 - max 135(word) | max 400(description)'}, 404
except AccessError as e:
logger.error(f'[{sql_user.nickname}] Can`t write data. Access denied "{e}"')
return {'error': f'A user with such a token does not have access rights to an example with this id'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data "{e}"')
return {'error': 'Failed to process your word object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] WORD IS READY TO BE UPDATED')
try:
db_worker.update_data(
data_type='word',
data_id=sql_word.word_id,
new_data=word
)
db_worker.update_data(
data_type='description',
data_id=sql_word.word_id,
new_data=description
)
sql_word = db_worker.get_word(
word_id=sql_word.word_id
)
returned_data = {
'word_id': sql_word.word_id,
'word': sql_word.word,
'description': sql_word.description,
'example_id': sql_word.example_id
}
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t write data from sql "{e}"')
return {'error': 'Failed to process your word object - check the correctness of the form data'}, 404
else:
logger.info(f'[{sql_user.nickname}] SUCCESS PUT WORD')
return returned_data, 200
def delete(self, token, word_id):
"""
Deletes word by word_id
:param token: string user token from db table apikeys
:param word_id: integer word id from db words
"""
try:
sql_user = db_worker.get_user_by_api_key(token=token)
except Exception as e:
logger.warning(f'[{token}] Can`t find user id "{e}"')
return {'error': 'Could not find a user with this key, please check your key and try again'}, 404
else:
logger.info(f'[{sql_user.nickname}] DELETE WORD')
try:
sql_word = db_worker.get_word(word_id=word_id)
sql_example = db_worker.get_example(example_id=int(sql_word.example_id))
if not sql_example.user_id == sql_user.user_id:
raise AccessError(f'Data owner: {sql_example.user_id}, Query owner: {sql_user.user_id}')
except AccessError as e:
logger.error(f'[{sql_user.nickname}] Can`t delete data. Access denied "{e}"')
return {'error': f'A user with such a token does not have access rights to an example with this id'}, 404
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t delete data "{e}"')
return {'error': 'Failed to process your word object - check the correctness of the data id'}, 404
else:
logger.info(f'[{sql_user.nickname}] WORD IS READY TO BE DELETED')
try:
db_worker.delete_data(
data_type='word',
data_id=word_id
)
sql_word = db_worker.get_word(word_id)
returned_data = {
'success': 'Your data has been successfully deleted'
}
if sql_word:
raise RuntimeError('Data was not successfully deleted from sql table')
except RuntimeError as e:
logger.error(f'[{sql_user.nickname}] Can`t delete data from sql "{e}"')
return {'error': 'Data was not successfully deleted from table, problem on our end, please try again'}, 500
except Exception as e:
logger.error(f'[{sql_user.nickname}] Can`t delete data from sql "{e}"')
return {'error': 'Failed to process your word object - check the correctness of the data id'}, 404
else:
logger.info(f'[{sql_user.nickname}] SUCCESS DELETE WORD')
return returned_data, 200
########################################################################################################################
def main():
"""
Assembly and launch of all functions of the part of the flask api
"""
# Create an api object
app = Flask(__name__)
api = Api(app)
# Add query interface
api.add_resource(Words, '/api/words/<string:token>')
api.add_resource(Lesson, '/api/lesson/<string:token>')
api.add_resource(Example, '/api/example/<string:token>/<int:example_id>')
api.add_resource(Word, '/api/word/<string:token>/<int:word_id>')
# Initialize and run
api.init_app(app)
app.run(
debug=True,
port=PORT,
host=HOST
)
########################################################################################################################
if __name__ == '__main__': # You can run separately only the api part from this module
logger.info("Starting api")
while True:
try:
main()
except Exception as e:
second = 2.5
logger.error(f'FlaskError. Restart after {second} (sec.) \n\n{e}\n\n')
time.sleep(second)