-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1152 lines (1109 loc) · 62.2 KB
/
app.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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
This is a custome API for Blogsites (still in development)
(Don't rush and try to run it! observe the code and fillin your credentials for SQL database; I've tested this with only Postgresql)
'''
from flask import Flask, request, redirect, url_for, make_response, session, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
import psycopg2
from psycopg2 import sql
import datetime
from datetime import timedelta
from werkzeug.security import generate_password_hash, check_password_hash
from flask_cors import CORS
from functools import wraps
import jwt
cookie_duration = timedelta(days=3)
app = Flask(__name__)
CORS(app,expose_headers=['Access-Control-Allow-Origin'],supports_credentials=True) #Required if working with cross-domain/cross-site requests! [Important]
app.permanent_session_lifetime = timedelta(days=3)
app.config['SECRET_KEY']='YourVeryOwnVeryLongTopSecretKey'
# change this to 'dev' if u wish to test the code with your local database and running the app on local machine other wise make it 'prod'...
ENV = 'prod'
if ENV == 'dev':
# for local databse connection(if testing and running on local machine instead of server)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://<username>:<password>@localhost/<database>'
else:
# for online databse connection
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://<username>:<password>@<host>/<database>'
app.debug = False
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Posts(db.Model):
'''This is a class for "posts" table'''
__tablename__ = 'posts'
_id = db.Column(db.Integer, primary_key=True,)
title = db.Column(db.Text())
author = db.Column(db.Text())
tags = db.Column(db.ARRAY(db.Text()))
content = db.Column(db.Text())
description = db.Column(db.Text())
thumbnail = db.Column(db.Text())
created = db.Column(db.DateTime(timezone=True),server_default=func.now())
def __init__(self, title, content, author, description=None,tags=None):
self.title = title
self.content = content
self.author = author
self.desciption = description
self.tags = tags
class Author(db.Model):
'''This is a class for Auther information'''
__tablename__ = 'authors'
auth_id = db.Column(db.Integer,primary_key=True)
public_id = db.Column(db.Integer,unique=True)
name = db.Column(db.Text())
rname = db.Column(db.Text())
password = db.Column(db.Text())
admin = db.Column(db.Boolean)
bio = db.Column(db.Text())
mail = db.Column(db.Text())
social = db.Column(db.ARRAY(db.Text()))
def __init__(self, name, mail, password, rname, bio,public_id,social,admin):
self.name = name
self.mail = mail
self.password = password
self.rname = rname
self.bio = bio
self.public_id = public_id
self.social = social
self.admin = admin
def get_searched_post(orderby='created' ,order='desc',author=None,tag=None,searchString=False):
'''actual implementation of getting-fetching all blogs/posts from posts table filtered by search items with other filters'''
try:
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
cur = conn.cursor()
if author:
if tag:
cur.execute(f'''SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT _id, title, description, author, tags, thumbnail, created) AS ColumnName (_id, title, description, author, tags, thumbnail, created) WHERE author='{author}' AND tags @> '{{"{tag}"}}' AND {searchString})) {'ORDER BY '+orderby+' '+order if orderby and order else False or 'ORDER BY '+orderby+' desc' if orderby else False or 'ORDER BY created '+order if order else False or 'ORDER BY created desc' }) FROM posts;''')
else:
cur.execute(f'''SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT _id, title, description, author, tags, thumbnail, created) AS ColumnName (_id, title, description, author, tags, thumbnail, created) WHERE author='{author}' AND {searchString})) {'ORDER BY '+orderby+' '+order if orderby and order else False or 'ORDER BY '+orderby+' desc' if orderby else False or 'ORDER BY created '+order if order else False or 'ORDER BY created desc' }) FROM posts;''')
elif tag:
cur.execute(f'''SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT _id, title, description, author, tags, thumbnail, created) AS ColumnName (_id, title, description, author, tags, thumbnail, created) WHERE tags @> '{{"{tag}"}}' AND {searchString})) {'ORDER BY '+orderby+' '+order if orderby and order else False or 'ORDER BY '+orderby+' desc' if orderby else False or 'ORDER BY created '+order if order else False or 'ORDER BY created desc' }) FROM posts;''')
else :
cur.execute(f"SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT _id, title, description, author, tags, thumbnail, created) AS ColumnName (_id, title, description, author, tags, thumbnail, created)WHERE {searchString})) {'ORDER BY '+orderby+' '+order if orderby and order else False or 'ORDER BY '+orderby+' desc' if orderby else False or 'ORDER BY created '+order if order else False or 'ORDER BY created desc' }) FROM posts;")
result = cur.fetchall()[0][0]
result = list(filter(None, result))
conn.commit()
cur.close()
conn.close()
print("search result:")
print(result)
return result if len(result)>0 else (500,{'Server Error':'posts not found'})
except psycopg2.OperationalError:
return 500,{'Server Error':'Database Error'}
except psycopg2.errors.UndefinedColumn:
return 500,{'Server Error':'Invalid Orderby'}
except psycopg2.errors.SyntaxError:
return 500,{'Server Error':'Invalid Search String'}
except psycopg2.errors.AmbiguousFunction:
return 500,{'Server Error':'Invalid Search String'}
def get_blog_posts(orderby='created' ,order='desc',author=None,tag=None):
'''actual implementation of getting-fetching all blogs/posts from posts table'''
try:
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
cur = conn.cursor()
if author:
if tag:
cur.execute(f'''SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT _id, title, description, author, tags, thumbnail, created) AS ColumnName (_id, title, description, author, tags, thumbnail, created) WHERE author='{author}' AND tags @> '{{"{tag}"}}')) {'ORDER BY '+orderby+' '+order if orderby and order else False or 'ORDER BY '+orderby+' desc' if orderby else False or 'ORDER BY created '+order if order else False or 'ORDER BY created desc' }) FROM posts;''')
else:
cur.execute(f'''SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT _id, title, description, author, tags, thumbnail, created) AS ColumnName (_id, title, description, author, tags, thumbnail, created) WHERE author='{author}')) {'ORDER BY '+orderby+' '+order if orderby and order else False or 'ORDER BY '+orderby+' desc' if orderby else False or 'ORDER BY created '+order if order else False or 'ORDER BY created desc' }) FROM posts;''')
elif tag:
cur.execute(f'''SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT _id, title, description, author, tags, thumbnail, created) AS ColumnName (_id, title, description, author, tags, thumbnail, created) WHERE tags @> '{{"{tag}"}}')) {'ORDER BY '+orderby+' '+order if orderby and order else False or 'ORDER BY '+orderby+' desc' if orderby else False or 'ORDER BY created '+order if order else False or 'ORDER BY created desc' }) FROM posts;''')
else :
cur.execute(f"SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT _id, title, description, author, tags, thumbnail, created) AS ColumnName (_id, title, description, author, tags, thumbnail, created))) {'ORDER BY '+orderby+' '+order if orderby and order else False or 'ORDER BY '+orderby+' desc' if orderby else False or 'ORDER BY created '+order if order else False or 'ORDER BY created desc' }) FROM posts;")
result = cur.fetchall()[0][0]
result = list(filter(None, result))
conn.commit()
cur.close()
conn.close()
print("get posts:")
print(result)
return result
except psycopg2.OperationalError:
return 500,{'Server Error':'Database Error'}
except psycopg2.errors.UndefinedColumn:
return 500,{'Server Error':'Invalid Orderby'}
def get_tags_from_db():
'''actual implementation of getting-fetching all tags used in posts table'''
try:
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
cur = conn.cursor()
cur.execute("SELECT json_agg(tags) FROM posts;")
result = cur.fetchall()[0][0]
new=set()
for i in result:
if type(i)==type(list()):
for ii in i:
new.add(ii)
result = list(new)
conn.commit()
cur.close()
conn.close()
print("get tags:")
print(result)
return result
except psycopg2.OperationalError:
return 500,{'Server Error':'Database Error'}
def getadmindata(name):
print('name->'+name)
try:
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
cur = conn.cursor()
cur.execute(f"SELECT json_agg(row_to_json((SELECT ColumnName FROM (SELECT auth_id,name,rname,bio,mail,social) AS ColumnName (auth_id,name,rname,bio,mail,social)))) FROM authors where name = '{name}' ;")
result = cur.fetchall()[0][0][0]
print(result)
new = dict()
for d,v in result.items():
if not type(v)==type(list()):
new[d] = v
else:
new_list = list()
for i in range(len(v[0])):
new_list.append(dict({'name':v[0][i],'url':v[1][i]}))
new[d] = new_list
result = new
conn.commit()
cur.close()
conn.close()
print("get admin data")
print(result)
return result
except psycopg2.OperationalError:
return 500,{'Server Error':'Database Error'}
except TypeError:
return False
def fetch_post_by_id(id):
'''actual implementation of getting-fetching post from posts table of gievn id'''
try:
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
cur = conn.cursor()
cur.execute(f"SELECT json_agg(posts) FROM posts where _id = {id}")
result = cur.fetchall()[0][0][0]
print('get post by id->'+id)
print(result)
conn.commit()
cur.close()
conn.close()
return result
except TypeError as error:
return 500,{'Server Error':f'{error}'}
def insert_post_to_database(title, content, description, tags, thumbnail, author):
'''actual implementation of insertion of data into posts table'''
try:
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
try:
cur = conn.cursor()
query = sql.SQL('''insert into posts (title, content, description, tags, thumbnail, author) values (%s,%s,%s,%s,%s,%s)''')
cur.execute(query, (title, content, description, tags, thumbnail, author))
conn.commit()
cur.close()
conn.close()
print('done uploading post')
return True
except:
print('failed uploading post')
return False
except:
print('failed connecting to db for create')
return False
def update_post_by_id(id,title, content, description, tags, thumbnail, author):
'''actual implementation of updation of post'''
try:
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
try:
cur = conn.cursor()
query = sql.SQL('''UPDATE posts SET title=%s, content=%s, description=%s, tags=%s, thumbnail=%s, author=%s WHERE _id=%s''')
cur.execute(query, (title, content, description, tags, thumbnail, author,id))
conn.commit()
cur.close()
conn.close()
print('done updating post')
return True
except:
print('failed updating post')
return False
except:
print('failed to connect for update')
return False
def postadmindata(name,rname,bio,password,admin,mail,social):
'''
This will upload author information into authors table...
'''
try:
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
try:
cur = conn.cursor()
query = sql.SQL('''insert into authors (name,rname,bio,password,admin,mail,social) values (%s,%s,%s,%s,%s,%s,%s)''')
cur.execute(query, (name,rname,bio,password,admin,mail,social))
conn.commit()
cur.close()
conn.close()
print('done posting admin')
return True
except:
print('failed posting admin')
return False
except:
print('failed to connect')
return False
def delete_all():
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
cur = conn.cursor()
cur.execute('select count(*) from posts')
n = cur.fetchall()[0][0]
if n != 0:
cur.execute("DELETE FROM posts RETURNING *")
r = cur.fetchall()
conn.commit()
cur.close()
conn.close()
print('deleted all posts')
if len(r)==0:
return make_response({"response":"No posts to delete!"})
return make_response({"response":"All Posts have been deleted!"})
else:
cur.close()
conn.close()
print('no posts to delete(for delete all)')
return make_response({'response':'No posts to delete'})
def delete_by(id):
if ENV == 'dev':
#local DB config.
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="localhost" ,port = "5432")
else:
#non-local DB config.(online)
conn = psycopg2.connect(database = "<database_name>", user = "<user>" , password = "<password>", host ="<host/server>" ,port = "5432")
cur = conn.cursor()
cur.execute('select count(*) from posts')
n = cur.fetchall()[0][0]
if n != 0:
cur.execute(f"DELETE FROM posts WHERE _id={id} RETURNING *")
r=cur.fetchall()
print('deletebyid')
conn.commit()
cur.close()
conn.close()
print('post '+str(id)+' deleted')
if len(r)==0:
return make_response({"response":"No such post to delete!"})
return make_response({"response":"The Post have been deleted!"})
else:
cur.close()
conn.close()
print('no post to delete(for delete post)')
return make_response({'response':'No posts to delete'})
class BlackListedTokenError(Exception):
'''
raise this Custom Error for indicating the Token is in the BlackList
'''
pass
#for storing logged out tokens till they get generated again by login randomly(rarecase)...
blackListedTokens = set()
#use this wrapper for the routes you want the jwt authentication(valid) as must!
def token_required(func):
@wraps(func)
def decorated(*args,**kwargs):
token = None
if 'token' in request.args:
token=request.args['token']
if not token:
return jsonify({'response':'token missing'})
try:
data = jwt.decode(token,app.config['SECRET_KEY'])
current_user= Author.query.filter_by(public_id=data['public_id'])
except jwt.ExpiredSignatureError:
return jsonify({'response':'token has expired!','success':False})
except jwt.InvalidSignatureError:
return jsonify({'response':'token is Invalid!','success':False})
except jwt.DecodeError:
return jsonify({'response':'token is Invalid!','success':False})
return func(current_user,*args,**kwargs)
return decorated
#use this wrapper for the routes you want the jwt authentication as optional !
def token_optional(func):
'''
for optional jwt authentication
on authentication failure it returns {msg='<fail reason>',token=False,admin=False,and all the *args & **kwargs recieved by original wrapped route!}
success returns {msg='<authors_name>',token=True,admin=<Bool_value(if that author is set admin or not)>,*args,**kwargs}
'''
@wraps(func)
def decorated(*args,**kwargs):
token = None
if 'token' in request.args:
token=request.args['token']
if not token:
return func(msg='token is missing',token=False,admin=False,*args,**kwargs)
try:
if token in blackListedTokens:
raise BlackListedTokenError('Reused Logged out Token')
data = jwt.decode(token,app.config['SECRET_KEY'])
author= Author.query.filter_by(public_id=data['public_id'])
if author:
print(author.first().name)
except jwt.ExpiredSignatureError:
return func(msg='token has Expired!',token=False,admin=False,*args,**kwargs)
except jwt.InvalidSignatureError:
return func(msg='token is Invalid!',token=False,admin=False,*args,**kwargs)
except jwt.DecodeError:
return func(msg='token is Invalid!',token=False,admin=False,*args,**kwargs)
except BlackListedTokenError:
return func(msg='token is Invalid!',token=False,admin=False,*args,**kwargs)
return func(msg=author.first().name if current_user else '',token=True,admin=author.first().admin,*args,**kwargs)
return decorated
@app.route('''/''')
@app.route('''/blog''')
@token_optional
def blog_page(msg,token,admin):
'''tempo blog page route'''
db.create_all()
in_query = request.args
if 'get' in in_query:
if in_query['get']=='tags':
result = get_tags_from_db()
resp = make_response({'success':True,f'tags':result})
resp.mimetype = 'application/json'
return resp
admin = '(admin-login not found)'
header = ''
try:
header = request.headers['<your_custom_auth_header_name>']
finally:
if token or '_id' in session or header == '<the fixed authentication header value that you want for your api>' :
admin='(admin-login found)'
return f"<div style='text-align:center;font-size:calc(100px - 6vw);'><h1>this is blog page</h1><br>{admin}<br><h3><br><br>see posts: <a href='/blog/posts'>/blog/posts</a><br>create a post: <a href='/blog/create'>/blog/create</a><br>admin login: <a href='/blog/admin'>/blog/admin</a></h3><div>"
@app.route('''/blog/posts''', methods=["GET"])
@token_optional
def return_blog_posts(msg,token,admin):
'''displaying all posts data from posts table as per request (queries acceptable)'''
db.create_all()
if token:
if not admin:
t_author=msg
in_query = request.args
if in_query:
searchString=''
if 'search' in in_query:
'''
if searching is to be done in db for articles it will be done using 'search' query followed by SearchString
the search will be case incase sensitive!
'''
searchData = in_query['search']
searchItems = searchData.split(' ')
contentSearch = ''
descriptionSearch = ''
titleSearch = ''
for i in searchItems:
if len(i)>0:
if i==searchItems[0]:
contentSearch += f""" LOWER(content) LIKE '%{i.lower()}%'"""
descriptionSearch += f""" or LOWER(description) LIKE '%{i.lower()}%'"""
titleSearch += f""" or LOWER(title) LIKE '%{i.lower()}%'"""
else:
contentSearch += f""" or LOWER(content) LIKE '%{i.lower()}%'""" if len(contentSearch)!=0 else f""" LOWER(content) LIKE '%{i.lower()}%'"""
descriptionSearch += f""" or LOWER(description) LIKE '%{i.lower()}%'"""
titleSearch += f""" or LOWER(title) LIKE '%{i.lower()}%'"""
searchString = contentSearch+descriptionSearch+titleSearch
if 'orderby' in in_query or 'order' in in_query or 'author' in in_query or 'tag' in in_query or 'search' in in_query or token:
if 'orderby' in in_query and 'order' in in_query and 'author' in in_query and 'tag' in in_query and 'search' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_searched_post(orderby=in_query["orderby"],order=in_query["order"],author=in_query['author'],tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'order' in in_query and 'orderby' in in_query and 'author' in in_query and 'search' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_searched_post(orderby=in_query["orderby"],order=in_query["order"],author=in_query['author'],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'order' in in_query and 'orderby' in in_query and 'tag' in in_query and 'search' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_searched_post(orderby=in_query["orderby"],order=in_query["order"],tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'order' in in_query and 'tag' in in_query and 'author' in in_query and 'search' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_searched_post(order=in_query["order"],author=in_query['author'],tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'orderby' in in_query and 'tag' in in_query and 'author' in in_query and 'search' in in_query:
result = get_searched_post(orderby=in_query["orderby"],author=in_query['author'],tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
elif 'author' in in_query and 'tag' in in_query and 'search' in in_query:
result = get_searched_post(author=in_query['author'],tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
elif 'order' in in_query and 'tag' in in_query and 'search' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_searched_post(order=in_query['order'],tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'orderby' in in_query and 'tag' in in_query and 'search' in in_query:
result = get_searched_post(order=in_query['order'],tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
elif 'order' in in_query and 'author' in in_query and 'search' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_searched_post(order=in_query['order'],author=in_query['author'],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'orderby' in in_query and 'author' in in_query and 'search' in in_query:
result = get_searched_post(orderby=in_query['orderby'],author=in_query['author'],searchString=searchString if len(searchString)>0 else False)
elif 'author' in in_query and 'search' in in_query:
result = get_searched_post(author=in_query['author'],searchString=searchString if len(searchString)>0 else False)
elif 'tag' in in_query and 'search' in in_query:
result = get_searched_post(tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
elif 'orderby' in in_query and 'order' in in_query and 'search' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_searched_post(orderby=in_query["orderby"],order=in_query["order"],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'orderby' in in_query and 'search' in in_query:
result = get_searched_post(orderby=in_query["orderby"],searchString=searchString if len(searchString)>0 else False)
elif 'order' in in_query and 'search' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_searched_post(order=in_query["order"],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameter'})
resp.mimetype = 'application/json'
return resp
elif 'author' in in_query and 'search' in in_query:
if in_query['author'].lower()=='aeyjey' or in_query['author'].lower() =='redranger' or in_query['author'].lower() == 'whoknows' :
result = get_searched_post(author=in_query['author'],searchString=searchString if len(searchString)>0 else False)
else:
resp = make_response({'success':False,'Server Error':'Author does not exists.'})
resp.mimetype = 'application/json'
return resp
elif 'tag' in in_query and 'search' in in_query:
result = get_searched_post(tag=in_query['tag'],searchString=searchString if len(searchString)>0 else False)
elif 'search' in in_query:
result = get_searched_post(searchString=searchString if len(searchString)>0 else False)
elif 'orderby' in in_query and 'order' in in_query and 'author' in in_query and 'tag' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_blog_posts(orderby=in_query["orderby"],order=in_query["order"],author=in_query['author'],tag=in_query['tag'])
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'order' in in_query and 'orderby' in in_query and 'author' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_blog_posts(orderby=in_query["orderby"],order=in_query["order"],author=in_query['author'])
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'order' in in_query and 'orderby' in in_query and 'tag' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_blog_posts(orderby=in_query["orderby"],order=in_query["order"],tag=in_query['tag'])
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'order' in in_query and 'tag' in in_query and 'author' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_blog_posts(order=in_query["order"],author=in_query['author'],tag=in_query['tag'])
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'orderby' in in_query and 'tag' in in_query and 'author' in in_query:
result = get_blog_posts(orderby=in_query["orderby"],author=in_query['author'],tag=in_query['tag'])
elif 'author' in in_query and 'tag' in in_query:
result = get_blog_posts(author=in_query['author'],tag=in_query['tag'])
elif 'order' in in_query and 'tag' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_blog_posts(order=in_query['order'],tag=in_query['tag'])
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'orderby' in in_query and 'tag' in in_query:
result = get_blog_posts(order=in_query['order'],tag=in_query['tag'])
elif 'order' in in_query and 'author' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
result = get_blog_posts(order=in_query['order'],author=in_query['author'])
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'orderby' in in_query and 'author' in in_query:
result = get_blog_posts(orderby=in_query['orderby'],author=in_query['author'])
elif 'author' in in_query :
result = get_blog_posts(author=in_query['author'])
elif 'tag' in in_query :
result = get_blog_posts(tag=in_query['tag'])
elif 'orderby' in in_query and 'order' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
if token:
if t_author:
print('logged author ('+t_author+') requested for his posts!')
result = get_blog_posts(order=in_query['order'],orderby=in_query['orderby'],author=t_author)
else:
print('logged Superuser requested for all posts!')
result = get_blog_posts(order=in_query['order'],orderby=in_query['orderby'])
else:
result = get_blog_posts(orderby=in_query["orderby"],order=in_query["order"],)
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameters'})
resp.mimetype = 'application/json'
return resp
elif 'orderby' in in_query:
if token:
if t_author:
print('logged author ('+t_author+') requested for his posts!')
result = get_blog_posts(orderby=in_query['orderby'],author=t_author)
else:
print('logged Superuser requested for all posts!')
result = get_blog_posts(orderby=in_query['orderby'])
else:
result = get_blog_posts(orderby=in_query["orderby"])
elif 'order' in in_query:
if in_query['order']=='desc' or in_query['order']=='asc' :
if token:
if t_author:
print('logged author ('+t_author+') requested for his posts!')
result = get_blog_posts(order=in_query['order'],author=t_author)
else:
print('logged Superuser requested for all posts!')
result = get_blog_posts(order=in_query['order'])
else:
result = get_blog_posts(order=in_query["order"])
else:
resp = make_response({'success':False,'Server Error':'invalid value for "order" query parameter'})
resp.mimetype = 'application/json'
return resp
elif 'author' in in_query:
if in_query['author'].lower()=='aeyjey' or in_query['author'].lower() =='redranger' or in_query['author'].lower() == 'whoknows' :
result = get_blog_posts(author=in_query['author'])
else:
resp = make_response({'success':False,'Server Error':'Author does not exists.'})
resp.mimetype = 'application/json'
return resp
elif 'tag' in in_query:
result = get_blog_posts(tag=in_query['tag'])
elif token and not('orderby' in in_query and 'order' in in_query and 'author' in in_query and 'tag' in in_query and 'search' in in_query):
if t_author:
print('logged author ('+t_author+') requested for his posts!')
result = get_blog_posts(author=t_author)
else:
print('logged Superuser requested for all posts!')
result = get_blog_posts()
else:
resp = make_response({'success':False,'Server Error':'invalid query parameter(s)'})
resp.mimetype = 'application/json'
return resp
else:
result = get_blog_posts()
try:
if result[0] == 500:
if result[1]['Server Error'] == "Database Error":
resp = make_response({'success':False,'Server Error':'Database Connection Error'})
elif result[1]['Server Error'] == "Invalid Orderby":
resp = make_response({'success':False,'Server Error':'Invalid value for "orderby" query parameter'})
elif result[1]['Server Error'] == "posts not found":
resp = make_response({'success':False,'response':'no posts for given search'})
elif result[1]['Server Error'] == "Invalid Search String":
resp = make_response({'success':False,'response':'invalid search string'})
else:
resp = make_response({'success':False,'Server Error':f'Unknown Error -> {result[1]}'})
else:
resp = make_response({'success':True,f'articles':result})
except TypeError:
if result is None:
resp = make_response({'success':False,'Server Error':'No Posts! Someone ate all the posts...'})
else:
resp = make_response({'success':True,f'articles':result})
except IndexError:
if len(result) == 0 :
resp = make_response({'success':False,'Server Error':'No Posts for given filter!...'})
finally:
resp.mimetype = 'application/json'
return resp
@app.route('''/blog/post''')
def get_post_by_id():
'''
gets the particular post in detail(same as /blog/posts but it will return the post of given id with its content!)
'''
print('post')
id = request.args
if 'id' in id:
print(id['id'])
id = id['id']
db.create_all()
result=fetch_post_by_id(id)
try:
if result[0] == 500:
if result[1]['Server Error'] == "'NoneType' object is not subscriptable":
resp = make_response({'success':False,'Server Error':f'The Post Does Not Exists'})
else:
resp = make_response({'success':False,'Server Error':'Unknown Error'})
except KeyError:
resp = make_response({'success':True,f'article':result})
finally:
resp.mimetype = 'application/json'
return resp
resp = make_response({'success':False,'Server Error':'missing query'})
resp.mimetype = 'application/json'
return resp
@app.route('''/blog/create''', methods=['POST'])
@token_optional
def upload_post(msg,token,admin):
'''
used for creating new article in database (in posts table)
can accepts data via FormData or Json(preference is for FormData if not will look for Json)
'''
db.create_all()
header = ''
try:
header = request.headers['<your_custom_auth_header_name>']
finally:
print(request.data)
if token or '_id' in session or header == '<the fixed authentication header value that you want for your api>' :
if request.form and 'title' in request.form and 'content' in request.form and 'author' in request.form and 'thumbnail' in request.form and 'tags' in request.form :
print('\n\nformdata found!\n\n')
title = request.form['title']
print(title)
content = request.form['content']
print(content)
author = request.form['author']
print(author)
tags = request.form['tags'].split(",")
print(tags)
if 'description' in request.form and request.form['description'] != "" :
description = request.form['description']
print(description)
else:
description = content[0:50] + '...'
print(description)
if request.form['thumbnail'] != "" :
thumbnail = request.form['thumbnail']
print(thumbnail)
else:
thumbnail = 'https://demo.plugins360.com/wp-content/uploads/2017/12/demo.png'
print(thumbnail)
r = insert_post_to_database(title, content, description, tags, thumbnail, author)
if r:
resp = make_response({'success':True,'result':'post uploaded'})
resp.mimetype = 'application/json'
return resp
else:
resp = make_response({'success':False,'result':'failed to upload post'})
resp.mimetype = 'application/json'
resp.status_code = 400
return resp
elif request.data and request.json:
req = request.get_json()
if req:
print('\n\njson found!\n\n')
if 'title' in req and 'content' in req and 'author' in req and 'thumbnail' in req and 'tags' in req :
title = req['title']
print(title)
content = req['content']
print(content)
author = req['author']
print(author)
if type(req['tags'])==list:
tags = req['tags']
print('tags list')
elif type(req['tags'])==str:
tags = req['tags'].split(",")
print('tags string -> list')
else:
tags = []
print(tags)
if 'description' in req and req['description'] != "" :
description = req['description']
print(description)
else:
description = content[0:50] + '...'
print(description)
if 'thumbnail' in req and req['thumbnail'] != "" :
thumbnail = req['thumbnail']
else:
thumbnail = 'https://demo.plugins360.com/wp-content/uploads/2017/12/demo.png'
print(thumbnail)
r = insert_post_to_database(title, content, description, tags, thumbnail, author)
if r:
resp = make_response({'success':True,'result':'post uploaded'})
resp.mimetype = 'application/json'
return resp
else:
resp = make_response({'success':False,'result':'failed to upload post'})
resp.mimetype = 'application/json'
resp.status_code = 400
return resp
else:
print('no json')
resp = make_response({'success':True,"result":"json compability under devlopement..."})
resp.mimetype = 'application/json'
resp.status_code = 200
return resp
else:
resp = make_response({'success':False,"result":"missing form data for 'title','content','author','tags','description','thumbnail' in the request"})
resp.mimetype = 'application/json'
resp.status_code = 500
return resp
else:
return make_response({'success':False,'response':'unauthorized access'})
@app.route('''/blog/update''', methods=['PUT','POST'])
@token_optional
def update_post(msg,token,admin):
'''
Used to update/modify the data (values) of article of given id(query param)
accepted FormData or Json (preference is given to FormData values if not present will lookout for Json)
only provide values for those attributes which are to be updated if provided attribute_name(like 'title') with no value then it will take it as empty(try to avoid such own errors)
'''
db.create_all()
id = request.args
if 'id' in id:
id = id['id']
header = ''
try:
header = request.headers['<your_custom_auth_header_name>']
finally:
req=request.get_json()
if token or '_id' in session or header == '<the fixed authentication header value that you want for your api>' :
rtitle=''
rcontent=''
rauthor=msg if token and not admin else ''
rdescription=''
rtags=''
rthumbnail=''
presult=fetch_post_by_id(id)
print(presult)
try:
if presult[0] == 500:
if presult[1]['Server Error'] == "'NoneType' object is not subscriptable":
resp = make_response({'success':False,'Server Error':f'The Post Does Not Exists'})
resp.mimetype = 'application/json'
return resp
else:
resp = make_response({'success':False,'Server Error':'Unknown Error'})
resp.mimetype = 'application/json'
return resp
except KeyError:
pass
if token and not admin:
if msg!=presult['author']:
return jsonify({'response':'''can't update post of another author! ''','success':False})
rtitle=presult['title']
rcontent=presult['content']
rdescription=presult['description']
rtags=presult['tags']
rauthor=presult['author']
rthumbnail=presult['thumbnail']
if request.form and 'title' in request.form or 'content' in request.form or 'author' in request.form or 'thumbnail' in request.form or 'tags' in request.form or 'description' in request.form:
print('formdata found for update')
rtitle = request.form['title'] if 'title' in request.form else rtitle
print(rtitle)
rcontent = request.form['content'] if 'content' in request.form else rcontent
print(rcontent)
rauthor = request.form['author'] if 'author' in request.form else rauthor
print(rauthor)
rtags = request.form['tags'].split(",") if 'tags' in request.form and type(request.form['tags'])==str else rtags
print(rtags)
if 'description' in request.form:
if request.form['description'] != "" :
rdescription = request.form['description']
print(rdescription)
else:
rdescription = rcontent[0:50] + '...' if len(rcontent) else ''
print(rdescription)
if 'thumbnail' in request.form:
if request.form['thumbnail'] != "" :
rthumbnail = request.form['thumbnail']
print(rthumbnail)
else:
rthumbnail = 'https://demo.plugins360.com/wp-content/uploads/2017/12/demo.png'
print(rthumbnail)
r = update_post_by_id(id,rtitle, rcontent, rdescription, rtags, rthumbnail, rauthor)
if r:
resp = make_response({'success':True,'result':'post updated'})
resp.mimetype = 'application/json'
return resp
else:
resp = make_response({'success':False,'result':'failed to update post'})
resp.mimetype = 'application/json'
resp.status_code = 500
return resp
elif req and 'title' in req or 'content' in req or 'author' in req or 'thumbnail' in req or 'tags' in req or 'description' in req:
print('json found for update')
rtitle = req['title'] if 'title' in req else rtitle
print(rtitle)
rcontent = req['content'] if 'content' in req else rcontent
print(rcontent)
rauthor = req['author'] if 'author' in req else rauthor
print(rauthor)
rtags = req['tags'].split(",") if 'tags' in req and type(req['tags'])==str else rtags
print(rtags)
if 'description' in req:
if req['description'] != "" :
rdescription = req['description']
print(rdescription)
else:
rdescription = rcontent[0:50] + '...' if len(rcontent) else ''
print(rdescription)
if 'thumbnail' in req:
if req['thumbnail'] != "" :
rthumbnail = req['thumbnail']
print(rthumbnail)
else:
rthumbnail = 'https://demo.plugins360.com/wp-content/uploads/2017/12/demo.png'
print(rthumbnail)
r = update_post_by_id(id,rtitle, rcontent, rdescription, rtags, rthumbnail, rauthor)
if r:
resp = make_response({'success':True,'result':'post updated'})
resp.mimetype = 'application/json'
return resp
else:
resp = make_response({'success':False,'result':'failed to update post'})
resp.mimetype = 'application/json'
resp.status_code = 500
return resp
else:
resp = make_response({'success':False,"result":"missing form data for 'title','content','author' in the request"})
resp.mimetype = 'application/json'
resp.status_code = 500
return resp
else:
return make_response({'success':False,'response':'unauthorized access'})
else:
return make_response({'success':False,'response':'missing value of id'})
@app.route('''/blog/create''', methods=["GET"])
@token_optional
def upload_post_page(msg,token,admin):
'''
for creating new article from origin(direct) api site!
(also has option to delete all current articles)
(Yes its possible to do(not recommended though), if you don't want that functionality just remove this route or comment it out...)
'''
db.create_all()
header = ''
try:
header = request.headers['<your_custom_auth_header_name>']
finally:
if token or '_id' in session or header == '<the fixed authentication header value that you want for your api>' :
return '''
<br><br><br><br><br><hr>
<form style="text-align: center;line-height: 1.5;" action="/blog/create" method="POST">
<p style="font-size:calc(130px - 8vw);">Create A Post</p>
<input style="font-size:calc(130px - 8vw);" type="text" name="title" placeholder="Enter Title" required /><br>
<input style="font-size:calc(130px - 8vw);" type="text" name="content" placeholder="Enter Content" required /><br>
<input type="text" name="author" placeholder="Enter Author" style="font-size:calc(130px - 8vw);" required><br>
<input type="text" name="tags" placeholder="Enter Tags(seperated by commas,no spaces)" style="font-size:calc(130px - 8vw);" required><br>
<input type="text" name="description" placeholder="Enter Description" style="font-size:calc(130px - 8vw);"><br>
<input type="text" name="thumbnail" placeholder="Enter Link to thumnail" style="font-size:calc(130px - 8vw);"><br><br>
<input style="font-size:calc(130px - 8vw);" type="submit" value="Create Article">
</form><hr>
<form style="text-align: center;line-height: 1.5;" action="/blog/post/delete" method="POST">
<input style="font-size:calc(130px - 8vw);" type="submit" value="Delete all Articles">
</form><hr>
'''
else:
return make_response({'success':False,'response':'unauthorized access'})
@app.route('''/blog/post/delete''', methods=["GET","POST"])
@token_optional
def delete_all_posts(msg,token,admin):
'''
Used to delete all Articles or just to delete one article of which id is provided through query param
'''
db.create_all()
id = request.args
if 'id' in id:
id = id['id']