-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
985 lines (896 loc) · 33.5 KB
/
main.py
File metadata and controls
985 lines (896 loc) · 33.5 KB
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
from pydantic import validate_email
from pydantic_core import PydanticCustomError
from db_connenction import db_connection, provide_transaction
from sqlalchemy.ext.asyncio import AsyncSession
import models as md, models_validation as mv # noqa: E401
from litestar import (
Litestar,
MediaType,
Request,
Response,
patch,
post,
get,
delete,
Controller,
)
from typing import Annotated, Any, Optional, Sequence
from litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin
from sqlalchemy import desc, select, insert, update, delete as sqdl
from litestar.openapi import OpenAPIConfig
from litestar.params import Parameter, Body
from litestar.exceptions import (
NotAuthorizedException,
ValidationException,
NotFoundException,
)
from litestar.handlers import BaseRouteHandler
from litestar.di import Provide
from sqlalchemy.exc import NoResultFound, IntegrityError
from passlib.hash import pbkdf2_sha256 as securepwd
from jwt_authentication import jwt_cookie_auth
from litestar.connection import ASGIConnection
# -----------------------------------------------------------------------------> GUARD
async def check_admin(connection: ASGIConnection, _: BaseRouteHandler) -> Any:
print("CHECK ADMIN ............................\n\n\n")
# print(connection.user)
if not connection.user.get("admin"):
raise NotAuthorizedException("⚠️ NOT ALLOWED")
# .......................................................................................... USER CONTROLLER 🔰
class usercontroller(Controller):
path = "/user"
tags = ["🟡 Users"]
async def check_user(self, user_id: str, request: Request) -> str:
# print("ENTERED")
if request.user["user_id"] and not request.user.get("admin"):
raise NotAuthorizedException("⚠️ NOT ALLOWED !!")
return user_id
dependencies = {"check_user_dep1": Provide(check_user, True)}
@post("/login", media_type=MediaType.TEXT)
async def login(
self, request: Request, data: mv.UserLogin, db: AsyncSession
) -> Any:
if data.pwd != data.cpwd:
raise ValidationException("⚠️ Passwords don't match")
userid = data.emailname
stmt = select(md.User).where(
(md.User.email == userid) | (md.User.username == userid)
)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO USER FOUND !!")
if not securepwd.verify(data.pwd, res.pwd):
raise ValidationException("⚠️ Incorrect Password !!")
return jwt_cookie_auth.login(
response_media_type=MediaType.TEXT,
response_body="✅ LOGGED IN AS ADMIN"
if res.admin
else "✅ LOGGED IN AS NON-ADMIN",
identifier=res.username,
token_extras={"admin": res.admin},
)
@post("/logout", media_type=MediaType.TEXT)
async def logout(self, request: Request) -> Any:
# print(request.user)
resp = Response("✅ LOGGED OUT")
resp.delete_cookie("token")
return resp
@get("/", guards=[check_admin])
async def users(self, request: Request, db: AsyncSession) -> list[md.User]:
# print("ENTERED ...........................\n")
# print(request.user)
res = await db.scalars(select(md.User))
return res._allrows()
@post("/register", exclude_from_auth=True, media_type=MediaType.TEXT)
async def register(self, data: mv.User, db: AsyncSession, request: Request) -> Any:
try:
validate_email(data.email)
except PydanticCustomError:
raise ValidationException("⚠️ Invalid Email")
if data.pwd != data.cpwd:
raise ValidationException("⚠️ Passwords don't match")
stmt = insert(md.User).values(
name=data.name,
username=data.username,
email=data.email,
pwd=securepwd.hash(data.pwd),
)
try:
await db.execute(stmt)
except IntegrityError:
return Response("⚠️ USER ALREADY EXISTS !!", status_code=400)
return "✅ USER ADDED SUCCESSFULLY !!"
@delete("/delete/{user_id:str}", status_code=200)
async def user_delete(
self,
db: AsyncSession,
check_user_dep1: Annotated[
Any, Parameter(description="Username/Email to delete")
],
) -> str:
user_id = check_user_dep1
# print(user_id)
stmt = select(md.User).where(
(md.User.email == user_id) | (md.User.username == user_id)
)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO USER FOUND !!")
await db.delete(res)
return "✅ DELETED USER SUCCESSFULLY !!"
# .......................................................................................... COURSE CONTROLLER 🔰
# -------------------------------------------------------------------> COURSE 🟢
class coursecontroller(Controller):
path = "/course"
tags = ["🟢 Courses"]
@get("/", exclude_from_auth=True)
async def courses(self, db: AsyncSession) -> list[md.Course]:
res = await db.scalars(select(md.Course))
ans = res._allrows()
return ans
@post("/add", guards=[check_admin], media_type=MediaType.TEXT)
async def course_add(self, data: mv.Course, db: AsyncSession) -> Any:
try:
data.duration = int(data.duration)
except ValueError:
raise ValidationException("⚠️ Duration can only be integer")
if data.duration < 1:
raise ValidationException("⚠️ Duration can't be less than than 1")
stmt = insert(md.Course).values(
name=data.name,
duration=data.duration,
type=data.type.value,
elig=data.elig,
)
try:
await db.execute(stmt)
except Exception:
return Response("⚠️ COURSE ALREADY EXISTS !!", status_code=400)
return "✅ ADDED SUCCESSFULLY !!"
@patch("/update/{course_id:int}", guards=[check_admin], media_type=MediaType.TEXT)
async def course_update(
self,
course_id: int,
db: AsyncSession,
data: dict = Body(
title="Course",
description='DEMO SCHEMA = { "name": " " , "duration": 0 , "type": " " , "elig": " " }',
),
) -> Any:
stmt = update(md.Course).where(md.Course.id == course_id).values(**data)
try:
await db.execute(stmt)
except Exception:
return Response("⚠️ NO COURSE WITH THIS ID EXISTS !!", status_code=404)
return "✅ UPDATED SUCCESSFULLY !!"
@delete(
"/delete/{course_id:int}",
status_code=200,
guards=[check_admin],
media_type=MediaType.TEXT,
)
async def course_delete(
self,
course_id: Annotated[int, Parameter(description="ID of Course to delete")],
db: AsyncSession,
) -> str | Response:
stmt = select(md.Course).where(md.Course.id == course_id)
res = await db.scalar(stmt)
if res is None:
return Response("⚠️ NO COURSE FOUND !!", status_code=404)
await db.delete(res)
return "✅ DELETED COURSE SUCCESSFULLY !!"
# -------------------------------------------------------------------> COURSEPOST 🟢
@get(
["/post/{course_id:int}"],
exclude_from_auth=True,
description="Get all the posts of specific course ",
)
async def posts(
self,
db: AsyncSession,
course_id: int = Parameter(description="ID of Course"),
) -> list[md.CoursePost]:
res = await db.scalars(
select(md.CoursePost).where(md.CoursePost.course_id == course_id)
)
ans = res._allrows()
return ans
@post(
["/post/{course_id:int}/add", "/post/{course_id:int}/{coursepost_id:int}/add"]
)
async def post_add(
self,
data: mv.Post,
request: Request,
db: AsyncSession,
coursepost_id: Optional[int] = Parameter(
description="ID of comment to reply to"
),
course_id: int = Parameter(description="ID of Course to comment on"),
) -> mv.Post:
user_id = request.user.get("user_id")
if coursepost_id is not None:
stmt = insert(md.CoursePost).values(
title=data.title,
body=data.body,
user_id=user_id,
coursepost_id=coursepost_id,
course_id=course_id,
)
else:
stmt = insert(md.CoursePost).values(
title=data.title,
body=data.body,
user_id=user_id,
course_id=course_id,
)
await db.scalar(stmt)
return data
@delete("/post/{post_id:int}/delete", status_code=201)
async def post_delete(
self,
post_id: Annotated[int, Parameter(description="ID of Post to delete")],
db: AsyncSession,
) -> str | Response:
stmt = select(md.CoursePost).where(md.CoursePost.id == post_id)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO POST FOUND !!")
await db.delete(res)
return "✅ DELETED POST SUCCESSFULLY !!"
# -------------------------------------------------------------------> COURSELIST 🟢
@get(["/list/all"], exclude_from_auth=True)
async def lists_all(
self,
request: Request,
db: AsyncSession,
) -> list[md.CourseList]:
res = await db.scalars(
select(md.CourseList).where(md.CourseList.view == "Public")
)
ans = res._allrows()
return ans
@get(["/list"])
async def lists_user(
self,
request: Request,
db: AsyncSession,
) -> list[md.CourseList]:
# user_id = request.user.get("user_id")
user_id = request.user["user_id"]
res = await db.scalars(
select(md.CourseList).where(md.CourseList.user_id == user_id)
)
ans = res._allrows()
return ans
@post(["/list/add"], media_type=MediaType.TEXT)
async def list_add(
self,
data: mv.List,
request: Request,
db: AsyncSession,
) -> Any:
try:
await db.get_one(md.Course, data.course_id)
except NoResultFound:
raise NotFoundException("⚠️ NO COURSE FOUND !!")
user_id = request.user.get("user_id")
stmt = insert(md.CourseList).values(
user_id=user_id, course_id=data.course_id, view=data.view.value
)
try:
await db.scalar(stmt)
except Exception:
return Response("⚠️ LIST ENTRY ALREADY EXISTS !!", status_code=400)
return "✅ ADDED SUCCESSFULLY !!"
@delete("/list/{course_id:int}/delete", status_code=200, media_type=MediaType.TEXT)
async def list_delete(
self,
request: Request,
db: AsyncSession,
course_id: int = Parameter(description="ID of Course in your list to delete"),
) -> Any:
try:
await db.get_one(md.Course, course_id)
except NoResultFound:
return Response("⚠️ NO COURSE FOUND !!", status_code=404)
user_id = request.user.get("user_id")
stmt = select(md.CourseList).where(
(md.CourseList.course_id == course_id) & (md.CourseList.user_id == user_id)
)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO LIST ENTRY FOUND !!")
await db.delete(res)
return "✅ DELETED LIST ENTRY SUCCESSFULLY !!"
# -------------------------------------------------------------------> COURSELIKES 🟢
@post("/likes", media_type=MediaType.TEXT)
async def likes_add(
self, course_id: int, request: Request, db: AsyncSession
) -> str | Response:
try:
await db.get_one(md.Course, course_id)
except NoResultFound:
raise NotFoundException("⚠️ NO COURSE FOUND !!")
user_id = request.user.get("user_id")
try:
await db.scalar(
insert(md.CourseLikes).values(user_id=user_id, course_id=course_id)
)
except IntegrityError:
return Response("⚠️ ALREADY LIKED !!", status_code=400)
stmt = (
update(md.Course)
.where(md.Course.id == course_id)
.values(likes=md.Course.likes + 1)
)
await db.execute(stmt)
return f"✅ LIKED COURSE {course_id}"
@get("/likes/ranking", exclude_from_auth=True, cache=20)
async def likes_ranking(self, db: AsyncSession) -> list[md.Course]:
stmt = select(md.Course).order_by(desc(md.Course.likes))
res = await db.scalars(stmt)
return res._allrows()
# .......................................................................................... COLLEGE CONTROLLER 🔰
class collegecontroller(Controller):
path = "/college"
tags = ["🟢 Colleges"]
@get("/", exclude_from_auth=True)
async def colleges(self, db: AsyncSession) -> list[md.College]:
res = await db.scalars(select(md.College))
return res._allrows()
@post("/add", guards=[check_admin], media_type=MediaType.TEXT)
async def college_add(
self,
db: AsyncSession,
data: mv.College = Body(title="College", default=1),
) -> Any:
try:
data.rank = int(data.rank)
except ValueError:
raise ValidationException("⚠️ Rank can only be integer")
if data.rank < 1:
raise ValidationException("⚠️ Rank can't be less than than 1")
stmt = insert(md.College).values(
name=data.name,
rank=data.rank,
email=data.email,
address=data.address,
city=data.city,
state=data.state,
country=data.country,
)
try:
await db.scalar(stmt)
except Exception:
return Response("⚠️ COLLEGE ALREADY EXISTS !!", status_code=400)
return "✅ ADDED SUCCESSFULLY !!"
@patch("/update/{college_id:int}", guards=[check_admin])
async def college_update(
self,
college_id: int,
db: AsyncSession,
data: dict = Parameter(description=f"DEMO SCHEMA = {mv.College.__slots__}"),
) -> Any:
stmt = update(md.College).where(md.College.id == college_id).values(**data)
await db.execute(stmt)
return data
@delete(
"/delete/{college_id:int}",
status_code=200,
guards=[check_admin],
media_type=MediaType.TEXT,
)
async def college_delete(
self,
db: AsyncSession,
college_id: int = Parameter(description="ID of College to delete"),
) -> str | Response:
stmt = select(md.College).where(md.College.id == college_id)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO COLLEGE FOUND !!")
await db.delete(res)
return "✅ DELETED COLLEGE SUCCESSFULLY !!"
# -------------------------------------------------------------------> COLLEGEPOST 🟢
@get(
["/post/{college_id:int}"],
exclude_from_auth=True,
description="Get all the posts of specific college ",
)
async def posts(
self,
db: AsyncSession,
college_id: int = Parameter(description="ID of Course"),
) -> list[md.CollegePost]:
res = await db.scalars(
select(md.CollegePost).where(md.CollegePost.college_id == college_id)
)
ans = res._allrows()
return ans
@post(
[
"/post/{college_id:int}/add",
"/post/{college_id:int}/{collegepost_id:int}/add",
]
)
async def post_add(
self,
data: mv.Post,
request: Request,
db: AsyncSession,
collegepost_id: Optional[int] = Parameter(
description="ID of comment to reply to"
),
college_id: int = Parameter(description="ID of College to comment on"),
) -> mv.Post:
user_id = request.user.get("user_id")
if collegepost_id is not None:
stmt = insert(md.CollegePost).values(
title=data.title,
body=data.body,
user_id=user_id,
college_id=college_id,
collegepost_id=collegepost_id,
)
else:
stmt = insert(md.CollegePost).values(
title=data.title,
body=data.body,
user_id=user_id,
college_id=college_id,
)
await db.scalar(stmt)
return data
@delete("/post/{post_id:int}/delete", status_code=201, media_type=MediaType.TEXT)
async def post_delete(
self,
post_id: Annotated[int, Parameter(description="ID of Post to delete")],
db: AsyncSession,
) -> str | Response:
stmt = select(md.CollegePost).where(md.CollegePost.id == post_id)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO POST FOUND !!")
await db.delete(res)
return "✅ DELETED POST SUCCESSFULLY !!"
# -------------------------------------------------------------------> COLLEGELIST 🟢
@get(["/list/all"], exclude_from_auth=True)
async def lists_all(
self,
db: AsyncSession,
) -> list[md.CollegeList]:
res = await db.scalars(
select(md.CollegeList).where(md.CollegeList.view == "Public")
)
ans = res._allrows()
return ans
@get(["/list"])
async def lists_user(
self,
request: Request,
db: AsyncSession,
) -> list[md.CollegeList]:
user_id = request.user.get("user_id")
res = await db.scalars(
select(md.CollegeList).where(md.CollegeList.user_id == user_id)
)
ans = res._allrows()
return ans
@post(["/list/add"], media_type=MediaType.TEXT)
async def list_add(
self,
data: mv.List,
request: Request,
db: AsyncSession,
) -> Any:
try:
await db.get_one(md.College, data.course_id)
except NoResultFound:
raise NotFoundException("⚠️ NO COLLEGE FOUND !!")
user_id = request.user.get("user_id")
stmt = insert(md.CollegeList).values(
user_id=user_id, college_id=data.course_id, view=data.view.value
)
try:
await db.scalar(stmt)
except Exception:
return Response("⚠️ LIST ENTRY ALREADY EXISTS !!", status_code=400)
return "✅ ADDED SUCCESSFULLY !!"
@delete("/list/{college_id:int}/delete", status_code=200, media_type=MediaType.TEXT)
async def list_delete(
self,
request: Request,
db: AsyncSession,
college_id: int = Parameter(description="ID of College in your list to delete"),
) -> Any:
try:
await db.get_one(md.College, college_id)
except NoResultFound:
raise NotFoundException("⚠️ NO COLLEGE FOUND !!")
user_id = request.user.get("user_id")
stmt = select(md.CollegeList).where(
(md.CollegeList.college_id == college_id)
& (md.CollegeList.user_id == user_id)
)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO LIST ENTRY FOUND !!")
await db.delete(res)
return "✅ DELETED LIST ENTRY SUCCESSFULLY !!"
# -------------------------------------------------------------------> COLLEGELIKES 🟢
@post("/likes", media_type=MediaType.TEXT)
async def likes_add(
self, college_id: int, request: Request, db: AsyncSession
) -> str | Response:
try:
await db.get_one(md.College, college_id)
except NoResultFound:
raise NotFoundException("⚠️ NO COLLEGE FOUND !!")
user_id = request.user.get("user_id")
try:
await db.scalar(
insert(md.CollegeLikes).values(user_id=user_id, college_id=college_id)
)
except IntegrityError:
return Response("⚠️ ALREADY LIKED !!", status_code=400)
stmt = (
update(md.College)
.where(md.College.id == college_id)
.values(likes=md.College.likes + 1)
)
await db.execute(stmt)
return f"✅ LIKED COLLEGE {college_id}"
@get("/likes/ranking", exclude_from_auth=True, cache=20)
async def likes_ranking(self, db: AsyncSession) -> list[md.College]:
stmt = select(md.College).order_by(desc(md.College.likes))
res = await db.scalars(stmt)
return res._allrows()
# .......................................................................................... EXAM CONTROLLER 🔰
class examcontroller(Controller):
path = "/exam"
tags = ["🟢 Exams"]
@get("/", exclude_from_auth=True)
async def exams(self, db: AsyncSession) -> Sequence[md.Exam]:
res = await db.scalars(select(md.Exam))
ans = res.all()
return ans
@post("/add", guards=[check_admin], media_type=MediaType.TEXT)
async def exam_add(self, data: mv.Exam, db: AsyncSession) -> str | Response:
stmt = insert(md.Exam).values(
name=data.name, elig=data.elig, syllabus=data.syllabus, fee=data.fee
)
try:
await db.scalar(stmt)
except Exception:
return Response("⚠️ EXAM ALREADY EXISTS !!", status_code=400)
return "✅ ADDED SUCCESSFULLY !!"
@patch("/update/{exam_id:int}", guards=[check_admin])
async def exam_update(
self,
exam_id: int,
db: AsyncSession,
data: dict = Parameter(description=f"DEMO SCHEMA = {mv.Exam.__slots__}"),
) -> Any:
stmt = update(md.Exam).where(md.Exam.id == exam_id).values(**data)
await db.execute(stmt)
return data
@delete(
"/delete/{exam_id:int}",
status_code=200,
guards=[check_admin],
media_type=MediaType.TEXT,
)
async def exam_delete(
self,
exam_id: Annotated[int, Parameter(description="ID of Exam to delete")],
db: AsyncSession,
) -> str | Response:
stmt = select(md.Exam).where(md.Exam.id == exam_id)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO EXAM FOUND !!")
await db.delete(res)
return "✅ DELETED SUCCESSFULLY !!"
# -------------------------------------------------------------------> EXAMPOST 🟢
@get(
["/post/{exam_id:int}"],
exclude_from_auth=True,
description="Get all the posts of specific college ",
)
async def posts(
self,
db: AsyncSession,
exam_id: int = Parameter(description="ID of Course"),
) -> list[md.ExamPost]:
res = await db.scalars(
select(md.ExamPost).where(md.ExamPost.exam_id == exam_id)
)
ans = res._allrows()
return ans
@post(
[
"/post/{exam_id:int}/add",
"/post/{exam_id:int}/{exampost_id:int}/add",
]
)
async def post_add(
self,
data: mv.Post,
request: Request,
db: AsyncSession,
exampost_id: Optional[int] = Parameter(description="ID of comment to reply to"),
exam_id: int = Parameter(description="ID of Exam to comment on"),
) -> mv.Post:
user_id = request.user.get("user_id")
if exampost_id is not None:
stmt = insert(md.ExamPost).values(
title=data.title,
body=data.body,
user_id=user_id,
exampost_id=exampost_id,
exam_id=exam_id,
)
else:
stmt = insert(md.ExamPost).values(
title=data.title,
body=data.body,
user_id=user_id,
exam_id=exam_id,
)
await db.scalar(stmt)
return data
@delete("/post/{post_id:int}/delete", status_code=201, media_type=MediaType.TEXT)
async def post_delete(
self,
post_id: Annotated[int, Parameter(description="ID of Post to delete")],
db: AsyncSession,
) -> str | Response:
stmt = select(md.ExamPost).where(md.ExamPost.id == post_id)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO POST FOUND !!")
await db.delete(res)
return "✅ DELETED POST SUCCESSFULLY !!"
# -------------------------------------------------------------------> EXAMLIST 🟢
@get(["/list/all"], exclude_from_auth=True)
async def lists_all(
self,
db: AsyncSession,
) -> list[md.ExamList]:
res = await db.scalars(select(md.ExamList).where(md.ExamList.view == "Public"))
ans = res._allrows()
return ans
@get(["/list"])
async def lists_user(
self,
request: Request,
db: AsyncSession,
) -> list[md.ExamList]:
user_id = request.user.get("user_id")
res = await db.scalars(
select(md.ExamList).where(md.ExamList.user_id == user_id)
)
ans = res._allrows()
return ans
@post(["/list/add"], media_type=MediaType.TEXT)
async def list_add(
self,
data: mv.List,
request: Request,
db: AsyncSession,
) -> Any:
try:
await db.get_one(md.Exam, data.course_id)
except NoResultFound:
raise NotFoundException("⚠️ NO EXAM FOUND !!")
user_id = request.user.get("user_id")
stmt = insert(md.ExamList).values(
user_id=user_id, exam_id=data.course_id, view=data.view.value
)
try:
await db.scalar(stmt)
except Exception:
return Response("⚠️ LIST ENTRY ALREADY EXISTS !!", status_code=400)
return "✅ ADDED SUCCESSFULLY !!"
@delete("/list/{exam_id:int}/delete", status_code=200, media_type=MediaType.TEXT)
async def list_delete(
self,
request: Request,
db: AsyncSession,
exam_id: int = Parameter(description="ID of Exam in your list to delete"),
) -> Any:
try:
await db.get_one(md.Exam, exam_id)
except NoResultFound:
raise NotFoundException("⚠️ NO EXAM FOUND !!")
user_id = request.user.get("user_id")
stmt = select(md.ExamList).where(
(md.ExamList.exam_id == exam_id) & (md.ExamList.user_id == user_id)
)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO LIST ENTRY FOUND !!")
await db.delete(res)
return "✅ DELETED LIST ENTRY SUCCESSFULLY !!"
# -------------------------------------------------------------------> EXAMLIKES 🟢
@post("/likes", media_type=MediaType.TEXT)
async def likes_add(
self, exam_id: int, request: Request, db: AsyncSession
) -> str | Response:
try:
await db.get_one(md.Exam, exam_id)
except NoResultFound:
raise NotFoundException("⚠️ NO EXAM FOUND !!")
user_id = request.user.get("user_id")
try:
await db.scalar(
insert(md.ExamLikes).values(user_id=user_id, exam_id=exam_id)
)
except IntegrityError:
return Response("⚠️ ALREADY LIKED !!", status_code=400)
stmt = (
update(md.Exam).where(md.Exam.id == exam_id).values(likes=md.Exam.likes + 1)
)
await db.execute(stmt)
return f"✅ LIKED EXAM {exam_id}"
@get("/likes/ranking", exclude_from_auth=True, cache=20)
async def likes_ranking(self, db: AsyncSession) -> list[md.Exam]:
stmt = select(md.Exam).order_by(desc(md.Exam.likes))
res = await db.scalars(stmt)
return res._allrows()
# .......................................................................................... ACADEMICS CONTROLLER 🔰
class academicscontroller(Controller):
path = "/academics"
tags = ["🟢 Academics"]
@get("/", exclude_from_auth=True)
async def academics(self, db: AsyncSession) -> Sequence[md.Academics]:
res = await db.scalars(select(md.Academics))
ans = res.all()
return ans
@post("/add", guards=[check_admin], media_type=MediaType.TEXT)
async def add(self, data: mv.Academics, db: AsyncSession) -> str | Response:
stmt = insert(md.Academics).values(
course_id=data.course_id,
college_id=data.college_id,
exam_id=data.exam_id,
course_fee=data.course_fee,
cutoff_rank=data.cutoff_rank,
)
try:
await db.execute(stmt)
except Exception:
return Response("⚠️ ACADEMICS ALREADY EXISTS !!", status_code=400)
return "✅ ADDED SUCCESSFULLY !!"
@delete("/delete/{academics_id:int}", status_code=200, guards=[check_admin])
async def delete(self, academics_id: int, db: AsyncSession) -> str | Response:
stmt = select(md.Academics).where(md.Academics.id == academics_id)
res = await db.scalar(stmt)
if res is None:
raise NotFoundException("⚠️ NO ACADEMICS FOUND !!")
else:
await db.delete(res)
return "✅ DELETED SUCCESSFULLY !!"
@get("/colleges-from-course", exclude_from_auth=True, cache=20)
async def CollegesFromCourse(
self,
db: AsyncSession,
course_id: int = Parameter(description="Get all Colleges offering this Course"),
) -> list[md.College]:
# ) -> list[Any]:
# stmt = select(md.College).where(
# md.College.id.in_(
# select(md.Academics.college_id).where(
# md.Academics.course_id == course_id
# )
# )
# )
# -----------------IN CLAUSE VS JOIN
stmt = (
select(md.College).join(
md.Academics,
(md.Academics.college_id == md.College.id)
& (md.Academics.course_id == course_id),
)
# .where(md.Academics.course_id == course_id)
)
# print(stmt)
res = await db.scalars(stmt)
ans = res._allrows()
return ans
@get("/academics-from-exam", exclude_from_auth=True, cache=20)
async def AcademicsFromExam(
self,
db: AsyncSession,
exam_id: int = Parameter(
description="All College & Courses accepting this Exam"
),
) -> list[dict]:
stmt = (
select(
md.College.id.label("College_id"),
md.College.name.label("College"),
md.Course.id.label("Course_id"),
md.Course.name.label("Course"),
)
.join(
md.Academics,
(md.Academics.college_id == md.College.id),
# & (md.Academics.exam_id == exam_id),
)
.join(
md.Course,
(md.Academics.course_id == md.Course.id)
& (md.Academics.exam_id == exam_id),
)
)
res = await db.execute(stmt)
ans = res.mappings()
ans = [dict(i) for i in ans]
return ans
@get("/fees-from-course", exclude_from_auth=True, cache=20)
async def FeesCourseCollege(
self,
db: AsyncSession,
course_id: int = Parameter(
description="All Colleges accepting the course (ASC sorted by fees)"
),
) -> list[Any]:
# stmt = (
# select(
# md.College.name.label("College"), md.Academics.course_fee.label("Fee")
# )
# .where(md.Academics.course_id == course_id)
# .join(md.College, md.Academics.college_id == md.College.id)
# .order_by(md.Academics.course_fee)
# )
subq = (
select(md.Academics.college_id, md.Academics.course_fee)
.where(md.Academics.course_id == course_id)
.alias()
)
stmt = (
select(md.College.name.label("College"), subq.c.course_fee.label("Fee"))
.join(subq, md.College.id == subq.c.college_id)
.order_by(subq.c.course_fee)
)
res = await db.execute(stmt)
ans = res.mappings()
ans = [dict(i) for i in ans]
return ans
# -----------------------------------------------------------------------------> EXCEPTION HANDLER
def exception_handler(_: Request, exc: Exception) -> Response:
status_code = getattr(exc, "status_code", 500)
detail = getattr(exc, "detail", "⚠️ SOME ERROR OCCURED")
return Response(
media_type=MediaType.TEXT,
content=detail,
status_code=status_code,
)
# -----------------------------------------------------------------------------> MAIN APP
app = Litestar(
route_handlers=[
usercontroller,
coursecontroller,
collegecontroller,
examcontroller,
academicscontroller,
],
dependencies={"db": Provide(provide_transaction)},
lifespan=[db_connection],
plugins=[SQLAlchemySerializationPlugin()],
on_app_init=[jwt_cookie_auth.on_app_init],
debug=True,
exception_handlers={
ValidationException: exception_handler,
NotAuthorizedException: exception_handler,
NotFoundException: exception_handler,
},
openapi_config=OpenAPIConfig(
title="AcademicWorld", version="", root_schema_site="rapidoc"
),
)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="localhost", port=8080, reload=True)