lyleokoth commited on
Commit
33f24e1
1 Parent(s): c2a5d36

Upload 103 files

Browse files
Files changed (44) hide show
  1. 02edbb24-36ac-4b3a-b344-31c1f26d198b.png +3 -0
  2. 21d5bfe5-5d49-4ff4-9425-6126cb42cd6b.png +3 -0
  3. 24644e99-3f0c-4b4b-89f2-21e867c2bb93.png +3 -0
  4. 24fd00b5-7c78-41e4-8b8b-9dc01a58bb09.png +3 -0
  5. 311cefe0-89cf-4f21-a6c0-d3150a24b58b.png +3 -0
  6. 346db193-43af-4288-9434-37c1d0327fb9.png +3 -0
  7. 35b643c4-f349-475f-ad54-561e0f89c228.png +3 -0
  8. 3b2197bd-f36b-4499-b7a7-4f907764e535.png +3 -0
  9. 41912548-ff7c-4d8f-9460-4dd10ff66cbb.png +3 -0
  10. 433ad831-76e2-4645-983c-f73639f14809.png +3 -0
  11. 4406b6b3-c17e-4b9c-bc6f-ff9359498875.png +3 -0
  12. 45bf1cbf-a25c-43ff-96a7-3347f1dc8a6f.png +3 -0
  13. 58042b46-df0a-48d2-9d05-c884835b62a2.png +3 -0
  14. 5970340c-dd8c-4354-9ea8-c3f0cdc63db6.png +3 -0
  15. 5a505a2c-0925-456f-99a6-7da1d8e7acfa.png +3 -0
  16. 64091096-90d9-4bf4-96b5-4bac075965a3.png +3 -0
  17. 67276fad-7ece-4f53-9426-c3c4758ba2a2.png +3 -0
  18. 6a9f4dcc-adae-473c-ad12-8e679a5abae0.png +3 -0
  19. 6d39d43f-4664-4ccb-b51e-170c9209a083.png +3 -0
  20. 87cc57cd-3038-4b45-bc0c-5e4f54c15cfe.png +3 -0
  21. 8a83eada-a368-4ff8-902f-820d7b9a8b4c.png +3 -0
  22. 8bc4fdf5-017b-471c-896f-4a79a708acdb.png +3 -0
  23. 8c3195fd-1959-4f06-9fd3-57964694a7c4.png +3 -0
  24. 8f577296-b627-489d-8e0f-8927f93f768f.png +3 -0
  25. 933ed423-6f8b-4a99-90f4-c427d7245c0d.png +3 -0
  26. 953e57d6-3b1c-40b1-a86d-912abadb7092.png +3 -0
  27. 96d9bd34-5f4e-41f2-b115-1bc1951b9a62.png +3 -0
  28. 99ed9265-42dd-48f6-937c-3a6c3174555f.png +3 -0
  29. c1c813fa-bcd1-4d43-845d-44f92a39fae6.png +3 -0
  30. c2dc3c16-ad06-4188-a9b0-351b4809ebaf.png +3 -0
  31. c795b855-cc1e-4937-b1a9-38efcbf970c2.png +3 -0
  32. cc711d16-d41b-44b3-99d1-f8e1215e9a0f.png +3 -0
  33. d082f4e2-f1b6-45e6-a323-6667c19eb97f.png +3 -0
  34. d1178954-f79b-416f-870b-617b834f43e5.png +3 -0
  35. dfe08b85-dceb-4127-8d07-7e4b994432b7.png +3 -0
  36. e3444294-c297-4ca0-b245-0b7484961111.png +3 -0
  37. e5d2caf4-eb4f-45f5-87d7-57765e86ee03.png +3 -0
  38. eb539461-d0c9-4cc4-88bc-660ca0f77eb4.png +3 -0
  39. ecf7e69b-799a-4042-8819-c23f04b73835.png +3 -0
  40. f71cfa41-9cc5-471b-902b-bb69c4c8c341.png +3 -0
  41. f7541013-5bde-485c-a9ff-e8749f8908b7.png +3 -0
  42. fc9c5d3e-fc14-48a9-9a81-f2e691fd45ee.png +3 -0
  43. ffa478d8-72f1-49ab-8c12-724b032079c3.png +3 -0
  44. metadata.jsonl +102 -0
02edbb24-36ac-4b3a-b344-31c1f26d198b.png ADDED

Git LFS Details

  • SHA256: 5fd03a922a2734c543bd282aecdc6d1793b47e0152c098130f20f75e0fd75845
  • Pointer size: 131 Bytes
  • Size of remote file: 232 kB
21d5bfe5-5d49-4ff4-9425-6126cb42cd6b.png ADDED

Git LFS Details

  • SHA256: 5001e8bee7d23a665596760fafb0dd8d8e56e31d340adcb72963c9ff0fd9cd7b
  • Pointer size: 131 Bytes
  • Size of remote file: 254 kB
24644e99-3f0c-4b4b-89f2-21e867c2bb93.png ADDED

Git LFS Details

  • SHA256: dc2c950609359b0ca079291178839686d5cb6d632efa22a8469041ca8e1aacf4
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
24fd00b5-7c78-41e4-8b8b-9dc01a58bb09.png ADDED

Git LFS Details

  • SHA256: 72eb6400a042c3896ec809fddd6dec96eef958822493661b3d049a48b4a2ef1f
  • Pointer size: 131 Bytes
  • Size of remote file: 296 kB
311cefe0-89cf-4f21-a6c0-d3150a24b58b.png ADDED

Git LFS Details

  • SHA256: 5fd03a922a2734c543bd282aecdc6d1793b47e0152c098130f20f75e0fd75845
  • Pointer size: 131 Bytes
  • Size of remote file: 232 kB
346db193-43af-4288-9434-37c1d0327fb9.png ADDED

Git LFS Details

  • SHA256: 5fd03a922a2734c543bd282aecdc6d1793b47e0152c098130f20f75e0fd75845
  • Pointer size: 131 Bytes
  • Size of remote file: 232 kB
35b643c4-f349-475f-ad54-561e0f89c228.png ADDED

Git LFS Details

  • SHA256: aaf0e322161f4087a1778f7346d9c4d4f0e8b432da167354f84ceec2dea845d2
  • Pointer size: 131 Bytes
  • Size of remote file: 171 kB
3b2197bd-f36b-4499-b7a7-4f907764e535.png ADDED

Git LFS Details

  • SHA256: ea077983da1675690cb3d64dde3601c882fb396720037a49ef3e8eae53851bcb
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
41912548-ff7c-4d8f-9460-4dd10ff66cbb.png ADDED

Git LFS Details

  • SHA256: 8ffd92a02532fcc465f9ad3008abddf06c53a1ec5f1f17e34daa64009d160558
  • Pointer size: 131 Bytes
  • Size of remote file: 242 kB
433ad831-76e2-4645-983c-f73639f14809.png ADDED

Git LFS Details

  • SHA256: e13536c7e1d71fbd2a0cac76f2722485af22099412f3adf2b8b852c267910b2a
  • Pointer size: 131 Bytes
  • Size of remote file: 236 kB
4406b6b3-c17e-4b9c-bc6f-ff9359498875.png ADDED

Git LFS Details

  • SHA256: 1491285e2fe55f74fd0a9d3034ffcdb98ea22388a274d484d6a23d39a3df3a2f
  • Pointer size: 130 Bytes
  • Size of remote file: 31.6 kB
45bf1cbf-a25c-43ff-96a7-3347f1dc8a6f.png ADDED

Git LFS Details

  • SHA256: f5090db17f0d5fe924a37566c7d2b895c0eb48825e21e598bdddd4cb986cb697
  • Pointer size: 131 Bytes
  • Size of remote file: 193 kB
58042b46-df0a-48d2-9d05-c884835b62a2.png ADDED

Git LFS Details

  • SHA256: 0856c913b8f18d01e9ea7ed3a8513249bcc0d891590321d8334ad68d2b42d2e6
  • Pointer size: 131 Bytes
  • Size of remote file: 141 kB
5970340c-dd8c-4354-9ea8-c3f0cdc63db6.png ADDED

Git LFS Details

  • SHA256: 6f64ff8c8b75628c5c1717e303d802ab2d6175f40b637d3d7c9182f591e32fb6
  • Pointer size: 131 Bytes
  • Size of remote file: 310 kB
5a505a2c-0925-456f-99a6-7da1d8e7acfa.png ADDED

Git LFS Details

  • SHA256: 4a1a1fe2365cb7cea6fb8e11cfdc15ce061f2aef416dc44bd225ead1dfca9fa1
  • Pointer size: 131 Bytes
  • Size of remote file: 174 kB
64091096-90d9-4bf4-96b5-4bac075965a3.png ADDED

Git LFS Details

  • SHA256: 3efaa90a854b226b7e25c8c9d7132f1af9b86f2cf83e0d5d0d9d06b9d79a9d18
  • Pointer size: 130 Bytes
  • Size of remote file: 89.2 kB
67276fad-7ece-4f53-9426-c3c4758ba2a2.png ADDED

Git LFS Details

  • SHA256: 1c439f397afbc2a4febe0523864ea8c7da9152185e3db87c2578c35a22ce3c23
  • Pointer size: 131 Bytes
  • Size of remote file: 157 kB
6a9f4dcc-adae-473c-ad12-8e679a5abae0.png ADDED

Git LFS Details

  • SHA256: c6b39d9359af25642c2cdf69aaf6e253ef1637ee3bda55420fb0c701d9af4fb3
  • Pointer size: 131 Bytes
  • Size of remote file: 133 kB
6d39d43f-4664-4ccb-b51e-170c9209a083.png ADDED

Git LFS Details

  • SHA256: ce915fe8c54eee920115cea696e6f2e9dece8dcc8698fe206e055f754750e140
  • Pointer size: 130 Bytes
  • Size of remote file: 98.9 kB
87cc57cd-3038-4b45-bc0c-5e4f54c15cfe.png ADDED

Git LFS Details

  • SHA256: 6a40f3aeaf2c14b19947c5a26a1372d637049c86f0fd9d99a7451e9bfff227be
  • Pointer size: 131 Bytes
  • Size of remote file: 118 kB
8a83eada-a368-4ff8-902f-820d7b9a8b4c.png ADDED

Git LFS Details

  • SHA256: 8e8eae67989086b79897273f7d1909099fab85bbe56c56b57633122403bebd85
  • Pointer size: 131 Bytes
  • Size of remote file: 362 kB
8bc4fdf5-017b-471c-896f-4a79a708acdb.png ADDED

Git LFS Details

  • SHA256: 6bdf8f4af38c7d2d2b5ed700b32092deee6271b7141bcc10e37f59804a1e6485
  • Pointer size: 131 Bytes
  • Size of remote file: 122 kB
8c3195fd-1959-4f06-9fd3-57964694a7c4.png ADDED

Git LFS Details

  • SHA256: 62370ce951216b42e2baf8551dc77bfedf6efdb8958d3864f7339980b03fe569
  • Pointer size: 131 Bytes
  • Size of remote file: 110 kB
8f577296-b627-489d-8e0f-8927f93f768f.png ADDED

Git LFS Details

  • SHA256: b66281b20e46855efb8b06723f25bb67ba85e30b2dff4e5192cd3b8efce15b38
  • Pointer size: 130 Bytes
  • Size of remote file: 67.4 kB
933ed423-6f8b-4a99-90f4-c427d7245c0d.png ADDED

Git LFS Details

  • SHA256: 6f64ff8c8b75628c5c1717e303d802ab2d6175f40b637d3d7c9182f591e32fb6
  • Pointer size: 131 Bytes
  • Size of remote file: 310 kB
953e57d6-3b1c-40b1-a86d-912abadb7092.png ADDED

Git LFS Details

  • SHA256: ea077983da1675690cb3d64dde3601c882fb396720037a49ef3e8eae53851bcb
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
96d9bd34-5f4e-41f2-b115-1bc1951b9a62.png ADDED

Git LFS Details

  • SHA256: 4a1a1fe2365cb7cea6fb8e11cfdc15ce061f2aef416dc44bd225ead1dfca9fa1
  • Pointer size: 131 Bytes
  • Size of remote file: 174 kB
99ed9265-42dd-48f6-937c-3a6c3174555f.png ADDED

Git LFS Details

  • SHA256: ea077983da1675690cb3d64dde3601c882fb396720037a49ef3e8eae53851bcb
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
c1c813fa-bcd1-4d43-845d-44f92a39fae6.png ADDED

Git LFS Details

  • SHA256: f1dea1d76f299718e52bdcb025116c7820ececc119459cdaad0fd0e9989dd973
  • Pointer size: 131 Bytes
  • Size of remote file: 240 kB
c2dc3c16-ad06-4188-a9b0-351b4809ebaf.png ADDED

Git LFS Details

  • SHA256: df74ad79a8b72959b4db070850078457756f2316f0fee161f4de724e6e2b1406
  • Pointer size: 131 Bytes
  • Size of remote file: 252 kB
c795b855-cc1e-4937-b1a9-38efcbf970c2.png ADDED

Git LFS Details

  • SHA256: 6bdf8f4af38c7d2d2b5ed700b32092deee6271b7141bcc10e37f59804a1e6485
  • Pointer size: 131 Bytes
  • Size of remote file: 122 kB
cc711d16-d41b-44b3-99d1-f8e1215e9a0f.png ADDED

Git LFS Details

  • SHA256: 72eb6400a042c3896ec809fddd6dec96eef958822493661b3d049a48b4a2ef1f
  • Pointer size: 131 Bytes
  • Size of remote file: 296 kB
d082f4e2-f1b6-45e6-a323-6667c19eb97f.png ADDED

Git LFS Details

  • SHA256: 78e995a7d48b971f62aa2281cc4aba16f50805a619fd6d374dc6128d42773491
  • Pointer size: 131 Bytes
  • Size of remote file: 198 kB
d1178954-f79b-416f-870b-617b834f43e5.png ADDED

Git LFS Details

  • SHA256: 8ffd92a02532fcc465f9ad3008abddf06c53a1ec5f1f17e34daa64009d160558
  • Pointer size: 131 Bytes
  • Size of remote file: 242 kB
dfe08b85-dceb-4127-8d07-7e4b994432b7.png ADDED

Git LFS Details

  • SHA256: 981e7cd1ea619f40338eb86944611c5b971d1f08a89e9d02b0f0086dfcf1e50e
  • Pointer size: 131 Bytes
  • Size of remote file: 134 kB
e3444294-c297-4ca0-b245-0b7484961111.png ADDED

Git LFS Details

  • SHA256: ea077983da1675690cb3d64dde3601c882fb396720037a49ef3e8eae53851bcb
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
e5d2caf4-eb4f-45f5-87d7-57765e86ee03.png ADDED

Git LFS Details

  • SHA256: d3718ffb8828690152bccbad60baf94148e308cd6e16d72a6f4af9ae66e9a488
  • Pointer size: 131 Bytes
  • Size of remote file: 248 kB
eb539461-d0c9-4cc4-88bc-660ca0f77eb4.png ADDED

Git LFS Details

  • SHA256: 4a7ee7bff9a9ecbcbac414798d56895aecc95b8b50f57eac1c52160472709cae
  • Pointer size: 131 Bytes
  • Size of remote file: 140 kB
ecf7e69b-799a-4042-8819-c23f04b73835.png ADDED

Git LFS Details

  • SHA256: ff08d8e0e182bda340e4c336ad6717db9c6421ea40ec620d641d3ee50136f934
  • Pointer size: 131 Bytes
  • Size of remote file: 253 kB
f71cfa41-9cc5-471b-902b-bb69c4c8c341.png ADDED

Git LFS Details

  • SHA256: 79731380e4e18caf9fa76569b58e3e47d19edc4ed0598af19b1438d64dfb789b
  • Pointer size: 131 Bytes
  • Size of remote file: 281 kB
f7541013-5bde-485c-a9ff-e8749f8908b7.png ADDED

Git LFS Details

  • SHA256: 4a7ee7bff9a9ecbcbac414798d56895aecc95b8b50f57eac1c52160472709cae
  • Pointer size: 131 Bytes
  • Size of remote file: 140 kB
fc9c5d3e-fc14-48a9-9a81-f2e691fd45ee.png ADDED

Git LFS Details

  • SHA256: 6fc0dd227690eb0fa7272060afd95fd2dea5fa663ce068f0c8ace8e9a629d839
  • Pointer size: 131 Bytes
  • Size of remote file: 237 kB
ffa478d8-72f1-49ab-8c12-724b032079c3.png ADDED

Git LFS Details

  • SHA256: 78e995a7d48b971f62aa2281cc4aba16f50805a619fd6d374dc6128d42773491
  • Pointer size: 131 Bytes
  • Size of remote file: 198 kB
metadata.jsonl ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"file_name": "94977984-81b4-474d-8739-ae37897c0939.png", "code": "def create_like(session: Session, activity: CreateActivity) -> Like:\r\n with session() as db:\r\n like: Like = Like(\r\n author_id=activity.user_id,\r\n post_id=activity.post_id\r\n )\r\n db.add(like)\r\n db.commit()\r\n db.refresh(like)\r\n return like"}
2
+ {"file_name": "66166aa0-8b0e-4ea6-b35c-942dd167fe09.png", "code": "def create_like(session: Session, activity: CreateActivity) -> Like:\r\n with session() as db:\r\n like: Like = Like(\r\n author_id=activity.user_id,\r\n post_id=activity.post_id\r\n )\r\n db.add(like)\r\n db.commit()\r\n db.refresh(like)\r\n return like"}
3
+ {"file_name": "214cccaa-a48a-458c-9143-1808d6214029.png", "code": "def create_like(session: Session, activity: CreateActivity) -> Like:\r\n with session() as db:\r\n like: Like = Like(\r\n author_id=activity.user_id,\r\n post_id=activity.post_id\r\n )\r\n db.add(like)\r\n db.commit()\r\n db.refresh(like)\r\n return like"}
4
+ {"file_name": "d895922a-a590-4ce0-9306-5bceaadcb047.png", "code": "def create_like(session: Session, activity: CreateActivity) -> Like:\r\n with session() as db:\r\n like: Like = Like(\r\n author_id=activity.user_id,\r\n post_id=activity.post_id\r\n )\r\n db.add(like)\r\n db.commit()\r\n db.refresh(like)\r\n return like"}
5
+ {"file_name": "35862378-8b62-40c0-832c-3b91946265ab.png", "code": "def create_like(session: Session, activity: CreateActivity) -> Like:\r\n with session() as db:\r\n like: Like = Like(\r\n author_id=activity.user_id,\r\n post_id=activity.post_id\r\n )\r\n db.add(like)\r\n db.commit()\r\n db.refresh(like)\r\n return like"}
6
+ {"file_name": "6117b2bb-fd83-46e1-a589-703b0f419eaa.png", "code": "def delete_like(session: Session, activity: CreateActivity) -> Like:\r\n with session() as db:\r\n like: Like = db.query(Like).filter(Like.author_id==activity.user_id, Like.post_id==activity.post_id).first()\r\n db.delete(like)\r\n db.commit()\r\n return like\r\n\r\ndef has_liked(session: Session, activity: CreateActivity) -> Like:\r\n with session() as db:\r\n like: Like = db.query(Like).filter(Like.author_id==activity.user_id, Like.post_id==activity.post_id).first()\r\n if like:\r\n return True\r\n return False"}
7
+ {"file_name": "6b4ff6ca-456c-478b-94f4-d0b8f23ed2ad.png", "code": "def list_user_likes(session: Session, user_data: GetUser) -> list[Like]:\r\n with session() as db:\r\n user: User = db.query(User).filter(User.id == user_data.user_id).first()\r\n likes: list[Like] = user.likes\r\n return likes\r\n\r\ndef list_post_likes(session: Session, post_data: GetPost):\r\n with session() as db:\r\n post: Post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n likes: list[Like] = post.likes\r\n for like in likes:\r\n like.author\r\n return likes\r\n\r\ndef get_key_like(session: Session, post_data: GetPost):\r\n from random import choice\r\n with session() as db:\r\n post: Post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n likes: list[Like] = post.likes\r\n for like in likes:\r\n like.author\r\n return choice(likes).author if likes else None"}
8
+ {"file_name": "4d14a5de-ff1a-4a7e-8c0d-659dcb31d750.png", "code": "def list_user_likes(session: Session, user_data: GetUser) -> list[Like]:\r\n with session() as db:\r\n user: User = db.query(User).filter(User.id == user_data.user_id).first()\r\n likes: list[Like] = user.likes\r\n return likes\r\n\r\ndef list_post_likes(session: Session, post_data: GetPost):\r\n with session() as db:\r\n post: Post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n likes: list[Like] = post.likes\r\n for like in likes:\r\n like.author\r\n return likes\r\n\r\ndef get_key_like(session: Session, post_data: GetPost):\r\n from random import choice\r\n with session() as db:\r\n post: Post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n likes: list[Like] = post.likes\r\n for like in likes:\r\n like.author\r\n return choice(likes).author if likes else None"}
9
+ {"file_name": "20caf41f-9ce4-4875-a023-aee89b324ea0.png", "code": "from sqlalchemy.orm import Session\r\nfrom ..models.post import Post\r\nfrom ..schemas.post import (\r\n CreatePost, GetPosts, GetPost, UpdatePost\r\n)\r\nfrom werkzeug.datastructures import FileStorage\r\nfrom flask import current_app\r\nfrom uuid import uuid4\r\nfrom werkzeug.utils import secure_filename\r\nimport os\r\nimport secrets\r\nfrom typing import Callable"}
10
+ {"file_name": "ea28d015-0623-4cea-a437-a5b2af247dbb.png", "code": "ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}\r\n\r\ndef get_file_extension(filename: str) -> str:\r\n if '.' in filename and filename.rsplit('.', 1)[1].lower():\r\n return filename.rsplit('.', 1)[1].lower()\r\n return ''\r\n\r\ndef allowed_file(filename: str) -> bool:\r\n file_extension: str = get_file_extension(filename)\r\n if file_extension and file_extension in ALLOWED_EXTENSIONS:\r\n return True\r\n return False\r\n\r\n\r\ndef save_post_photo_locally(post_image: dict) -> None:\r\n \"\"\"Save the uploadeded post image.\"\"\"\r\n file: FileStorage = post_image['post_image']\r\n upload_folder = os.path.join(current_app.root_path, 'static', 'img')\r\n if file and allowed_file(file.filename):\r\n filename = f'{secrets.token_hex(8)}.{get_file_extension(file.filename)}' \r\n # Use celery task\r\n file.save(os.path.join(upload_folder, filename))\r\n return filename\r\n return ''"}
11
+ {"file_name": "c9adde79-584b-47ba-ae7c-91f2a12ee0cb.png", "code": "def save_post_photo_aws_s3(post_image: dict) -> None:\r\n \"\"\"Save the uploadeded post image.\"\"\"\r\n file: FileStorage = post_image['post_image']\r\n if file and allowed_file(file.filename):\r\n filename = f'{secrets.token_hex(8)}.{get_file_extension(file.filename)}'\r\n # Use celery task\r\n return filename\r\n return ''\r\n\r\ndef no_save_post_photo(post_image: dict) -> None:\r\n \"\"\"Save the uploadeded post image.\"\"\"\r\n file: FileStorage = post_image['post_image']\r\n if file and allowed_file(file.filename):\r\n filename = f'{secrets.token_hex(8)}.{get_file_extension(file.filename)}'\r\n return filename\r\n return ''\r\n\r\n\r\ndef save_post_photo(post_image: dict, save_location: str = '') -> str:\r\n \"\"\"Save the uploadeded post image.\"\"\"\r\n save_photo_funcs: dict[str, Callable[[dict], str]] = {\r\n 'locally': save_post_photo_locally,\r\n 'aws_s3': save_post_photo_aws_s3,\r\n 'default': no_save_post_photo\r\n }\r\n if save_photo_funcs.get(save_location):\r\n filename: str = save_photo_funcs[save_location](post_image)\r\n else:\r\n filename: str = save_photo_funcs['default'](post_image)\r\n return filename"}
12
+ {"file_name": "b344b10d-8a13-46e1-ae86-5bdf5fae917f.png", "code": "def create_post(post_data: CreatePost, post_image: dict, session: Session):\r\n post_image_url: str = save_post_photo(post_image)\r\n post: Post = Post(\r\n id='Post_' + str(uuid4()),\r\n author_id=post_data.author_id,\r\n location=post_data.location,\r\n text=post_data.text,\r\n image_url=post_image_url\r\n )\r\n with session() as db:\r\n db.add(post)\r\n db.commit()\r\n db.refresh(post)\r\n return post"}
13
+ {"file_name": "889441e8-6314-4628-b0c0-f6e3115f951a.png", "code": "def create_post(post_data: CreatePost, post_image: dict, session: Session):\r\n post_image_url: str = save_post_photo(post_image)\r\n post: Post = Post(\r\n id='Post_' + str(uuid4()),\r\n author_id=post_data.author_id,\r\n location=post_data.location,\r\n text=post_data.text,\r\n image_url=post_image_url\r\n )\r\n with session() as db:\r\n db.add(post)\r\n db.commit()\r\n db.refresh(post)\r\n return post"}
14
+ {"file_name": "a4f6995c-8ab2-400a-bbdb-5cc6757d638d.png", "code": "def create_post(post_data: CreatePost, post_image: dict, session: Session):\r\n post_image_url: str = save_post_photo(post_image)\r\n post: Post = Post(\r\n id='Post_' + str(uuid4()),\r\n author_id=post_data.author_id,\r\n location=post_data.location,\r\n text=post_data.text,\r\n image_url=post_image_url\r\n )\r\n with session() as db:\r\n db.add(post)\r\n db.commit()\r\n db.refresh(post)\r\n return post"}
15
+ {"file_name": "b0558326-bfc4-4a67-8f1f-783c927f87ba.png", "code": "def create_post(post_data: CreatePost, post_image: dict, session: Session):\r\n post_image_url: str = save_post_photo(post_image)\r\n post: Post = Post(\r\n id='Post_' + str(uuid4()),\r\n author_id=post_data.author_id,\r\n location=post_data.location,\r\n text=post_data.text,\r\n image_url=post_image_url\r\n )\r\n with session() as db:\r\n db.add(post)\r\n db.commit()\r\n db.refresh(post)\r\n return post"}
16
+ {"file_name": "2a9a7201-5c02-448e-af76-4ca708d67d23.png", "code": "def create_post(post_data: CreatePost, post_image: dict, session: Session):\r\n post_image_url: str = save_post_photo(post_image)\r\n post: Post = Post(\r\n id='Post_' + str(uuid4()),\r\n author_id=post_data.author_id,\r\n location=post_data.location,\r\n text=post_data.text,\r\n image_url=post_image_url\r\n )\r\n with session() as db:\r\n db.add(post)\r\n db.commit()\r\n db.refresh(post)\r\n return post"}
17
+ {"file_name": "f010a565-b8f6-4a0c-ad90-7a50eb13c249.png", "code": "def update_post(post_data: UpdatePost, post_image: dict, session: Session):\r\n post_image_url: str = save_post_photo(post_image)\r\n with session() as db:\r\n post: Post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n if post_data.location:\r\n post.location = post_data.location\r\n if post_data.text:\r\n post.text = post_data.text\r\n if post_image_url:\r\n post.image_url = post_image_url\r\n db.commit()\r\n db.refresh(post)\r\n return post\r\n\r\ndef get_post(session: Session, post_data: GetPost):\r\n with session() as db:\r\n post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n return post"}
18
+ {"file_name": "3668a7ea-5d72-42a8-b26c-bafba9f327cd.png", "code": "def get_posts(session: Session, post_data: GetPosts):\r\n with session() as db:\r\n posts: list[Post] = db.query(Post).offset(post_data.offset).limit(post_data.limit).all()\r\n for post in posts:\r\n post.author\r\n return posts\r\n\r\ndef delete_post(session: Session, post_data: GetPost):\r\n with session() as db:\r\n post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n db.delete(post)\r\n db.commit()\r\n \r\n return post"}
19
+ {"file_name": "8bd9a171-5d31-41c0-8963-c49cda7ee71d.png", "code": "def get_posts(session: Session, post_data: GetPosts):\r\n with session() as db:\r\n posts: list[Post] = db.query(Post).offset(post_data.offset).limit(post_data.limit).all()\r\n for post in posts:\r\n post.author\r\n return posts\r\n\r\ndef delete_post(session: Session, post_data: GetPost):\r\n with session() as db:\r\n post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n db.delete(post)\r\n db.commit()\r\n \r\n return post"}
20
+ {"file_name": "edba516f-516e-41d9-9d2f-7c788785b717.png", "code": "def get_posts(session: Session, post_data: GetPosts):\r\n with session() as db:\r\n posts: list[Post] = db.query(Post).offset(post_data.offset).limit(post_data.limit).all()\r\n for post in posts:\r\n post.author\r\n return posts\r\n\r\ndef delete_post(session: Session, post_data: GetPost):\r\n with session() as db:\r\n post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n db.delete(post)\r\n db.commit()\r\n \r\n return post"}
21
+ {"file_name": "8a7cc60c-3f28-4fb6-81d6-535d7cdde5df.png", "code": "from ..schemas.user import UserCreate\r\nfrom sqlalchemy.orm import Session\r\nfrom ....extensions.extensions import bcrypt\r\nfrom ..models.user import User\r\nfrom ..schemas.user import User as Userschemas\r\nfrom ..schemas.user import (\r\n GetUser, GetUsers, ActivateUser, LoginUser, RequestPasswordReset, PasswordReset\r\n)\r\nfrom typing import Optional\r\nfrom jwt import ExpiredSignatureError, InvalidTokenError\r\nfrom uuid import uuid4\r\nfrom typing import Callable"}
22
+ {"file_name": "14f6a2a5-e984-4021-9f59-ec8bcd7d5ebd.png", "code": "def send_email_local(user_email_address: str, message: str) -> None:\r\n pass\r\n\r\ndef send_email_aws_ses(user_email_address: str, message: str) -> None:\r\n pass\r\n\r\ndef send_account_activation_email(user_email_address: str, message: str) -> None:\r\n pass\r\n\r\ndef send_password_reset_email(user_email_address: str, message: str) -> None:\r\n pass\r\n\r\ndef generate_account_activation_email(message: str) -> None:\r\n pass\r\n\r\ndef generate_password_reset_email(message: str) -> None:\r\n pass"}
23
+ {"file_name": "c6b7a3b6-1baf-44ea-888b-885f79aa62c8.png", "code": "def send_email_local(user_email_address: str, message: str) -> None:\r\n pass\r\n\r\ndef send_email_aws_ses(user_email_address: str, message: str) -> None:\r\n pass\r\n\r\ndef send_account_activation_email(user_email_address: str, message: str) -> None:\r\n pass\r\n\r\ndef send_password_reset_email(user_email_address: str, message: str) -> None:\r\n pass\r\n\r\ndef generate_account_activation_email(message: str) -> None:\r\n pass\r\n\r\ndef generate_password_reset_email(message: str) -> None:\r\n pass"}
24
+ {"file_name": "5b934805-79b7-4e7e-b776-ccdaf1c0ab59.png", "code": "def generate_email(user_email_address: str, email_type: str) -> str:\r\n email_types: dict[str, Callable] = {\r\n 'password_reset': send_password_reset_email,\r\n 'account_activation': send_account_activation_email\r\n }\r\n return email_types[email_type]\r\n\r\ndef send_email(user_email_address: str, email_sender: str) -> None:\r\n email_senders: dict[str, Callable] = {\r\n 'local': send_email_local,\r\n 'aws_ses': send_email_aws_ses\r\n }\r\n return email_sender[email_sender]"}
25
+ {"file_name": "680f1dde-379b-4424-ba03-6e91aa57d85d.png", "code": "def create_user(user_data: UserCreate, session: Session):\r\n hashed_password = User.hash_password(user_data.password)\r\n user = User(\r\n id='User_' + str(uuid4()),\r\n first_name=user_data.first_name,\r\n last_name=user_data.last_name,\r\n email_address=user_data.email_address,\r\n password=hashed_password\r\n )\r\n with session() as db:\r\n db.add(user)\r\n db.commit()\r\n db.refresh(user)\r\n return user\r\n\r\ndef get_user_by_email(session: Session, email: str):\r\n with session() as db:\r\n user = db.query(User).filter(User.email_address == email).first()\r\n return user"}
26
+ {"file_name": "346b7027-da81-442d-8b97-f14ffd644954.png", "code": "def get_random_user(session: Session):\r\n from random import choice\r\n with session() as db:\r\n user = choice(db.query(User).all())\r\n return user\r\n\r\ndef get_user(session: Session, user_data: GetUser):\r\n with session() as db:\r\n user = db.query(User).filter(User.id == user_data.user_id).first()\r\n return user\r\n\r\ndef get_users(session: Session, user_data: GetUsers):\r\n with session() as db:\r\n users = db.query(User).offset(user_data.offset).limit(user_data.limit).all()\r\n return users"}
27
+ {"file_name": "6d62e8bb-9325-4d04-a137-f61ea2a2e7f8.png", "code": "def delete_user(session: Session, user_data: GetUser):\r\n with session() as db:\r\n user = db.query(User).filter(User.id == user_data.user_id).first()\r\n db.delete(user)\r\n db.commit()\r\n \r\n return user\r\n\r\n\r\ndef user_account_active(session: Session, user_data: GetUser):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.id == user_data.user_id).first()\r\n return user.activated"}
28
+ {"file_name": "f2e1847d-9018-4789-8ea5-f2256daeb8a2.png", "code": "def delete_user(session: Session, user_data: GetUser):\r\n with session() as db:\r\n user = db.query(User).filter(User.id == user_data.user_id).first()\r\n db.delete(user)\r\n db.commit()\r\n \r\n return user\r\n\r\n\r\ndef user_account_active(session: Session, user_data: GetUser):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.id == user_data.user_id).first()\r\n return user.activated"}
29
+ {"file_name": "1f667095-97c3-4938-a1a2-1ed6ed57a2fd.png", "code": "def activate_user_account(session: Session, activation_data: ActivateUser):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.id == activation_data.user_id).first()\r\n if user.id == User.decode_auth_token(activation_data.activation_token):\r\n user.activated = True\r\n db.commit()\r\n return True\r\n raise InvalidTokenError('Invalid or Expired token.')\r\n\r\n\r\ndef loggin_user(session: Session, login_data: LoginUser):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.email_address == login_data.email_address).first()\r\n if user and user.check_password(login_data.password):\r\n return True\r\n raise ValueError('Invalid email address and or password.')\r\n"}
30
+ {"file_name": "572f77d2-f1d5-41e8-b6aa-4c7472c62ca3.png", "code": "def activate_user_account(session: Session, activation_data: ActivateUser):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.id == activation_data.user_id).first()\r\n if user.id == User.decode_auth_token(activation_data.activation_token):\r\n user.activated = True\r\n db.commit()\r\n return True\r\n raise InvalidTokenError('Invalid or Expired token.')\r\n\r\n\r\ndef loggin_user(session: Session, login_data: LoginUser):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.email_address == login_data.email_address).first()\r\n if user and user.check_password(login_data.password):\r\n return True\r\n raise ValueError('Invalid email address and or password.')\r\n"}
31
+ {"file_name": "41544d3f-b603-4392-a08d-1b2bedfb7e49.png", "code": "def generate_password_reset_token(session: Session, reset_password_request: RequestPasswordReset):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.email_address == reset_password_request.email_address).first()\r\n resp = {\r\n 'user_id': user.id,\r\n 'email_address': user.email_address,\r\n 'password_reset_token': user.generate_password_reset_token()\r\n }\r\n return resp\r\n\r\n\r\ndef password_repeated(session: Session, password_reset: PasswordReset):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.email_address == password_reset.email_address).first()\r\n return user.check_password(password_reset.password)"}
32
+ {"file_name": "7341b4b1-8719-4363-aa81-260d5b61e047.png", "code": "def reset_password(session: Session, password_reset: PasswordReset):\r\n with session() as db:\r\n user: User = db.query(User).filter(User.email_address == password_reset.email_address).first()\r\n email_address = user.decode_password_token(password_reset.password_reset_token)\r\n if email_address == user.email_address:\r\n user.password = user.hash_password(password_reset.password)\r\n db.commit()\r\n return True"}
33
+ {"file_name": "2540dfa6-3610-48b7-b05d-7191443304dd.png", "code": "from ..schemas.activity import CreateActivity, GetRepeatableActivity\r\nfrom sqlalchemy.orm import Session\r\nfrom ..models.view import View\r\nfrom ..models.user import User\r\nfrom ..models.post import Post\r\nfrom ..schemas.user import GetUser\r\nfrom ..schemas.post import GetPost\r\nfrom uuid import uuid4\r\n\r\n\r\ndef create_view(session: Session, activity: CreateActivity) -> View:\r\n with session() as db:\r\n view: View = View(\r\n author_id=activity.user_id,\r\n post_id=activity.post_id,\r\n id='View_' + str(uuid4())\r\n )\r\n db.add(view)\r\n db.commit()\r\n db.refresh(view)\r\n return view"}
34
+ {"file_name": "5fd5ccd2-e48d-4dd8-979a-143e4525cefb.png", "code": "from ..schemas.activity import CreateActivity, GetRepeatableActivity\r\nfrom sqlalchemy.orm import Session\r\nfrom ..models.view import View\r\nfrom ..models.user import User\r\nfrom ..models.post import Post\r\nfrom ..schemas.user import GetUser\r\nfrom ..schemas.post import GetPost\r\nfrom uuid import uuid4\r\n\r\n\r\ndef create_view(session: Session, activity: CreateActivity) -> View:\r\n with session() as db:\r\n view: View = View(\r\n author_id=activity.user_id,\r\n post_id=activity.post_id,\r\n id='View_' + str(uuid4())\r\n )\r\n db.add(view)\r\n db.commit()\r\n db.refresh(view)\r\n return view"}
35
+ {"file_name": "22bf19c1-2192-40b6-bb33-df081156930d.png", "code": "def has_viewed(session: Session, activity: CreateActivity) -> View:\r\n with session() as db:\r\n view: View = db.query(View).filter(View.author_id==activity.user_id, View.post_id==activity.post_id).first()\r\n if view:\r\n return True\r\n return False\r\n\r\ndef list_user_views(session: Session, user_data: GetUser) -> list[View]:\r\n with session() as db:\r\n user: User = db.query(User).filter(User.id == user_data.user_id).first()\r\n views: list[View] = user.views\r\n return views\r\n\r\ndef list_post_views(session: Session, post_data: GetPost):\r\n with session() as db:\r\n post: Post = db.query(Post).filter(Post.id == post_data.post_id).first()\r\n views: list[View] = post.views\r\n return views"}
36
+ {"file_name": "bec2d9f6-8daa-4666-9b10-e1eb52f5284a.png", "code": "from .user import User\r\nfrom .post import Post\r\nfrom .like import Like\r\nfrom .bookmark import Bookmark\r\nfrom .view import View\r\nfrom .view import View\r\nfrom .comment import Comment"}
37
+ {"file_name": "50f83148-75cd-4f84-b660-8ca15b0472be.png", "code": "from datetime import datetime\r\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\r\nfrom ..database import Base\r\nfrom sqlalchemy import ForeignKey\r\n\r\n\r\nclass Bookmark(Base):\r\n __tablename__ = 'bookmarks'\r\n \r\n author_id: Mapped[str] = mapped_column(ForeignKey('users.id'), primary_key=True)\r\n post_id: Mapped[str] = mapped_column(ForeignKey('posts.id'), primary_key=True)\r\n bookmark_date: Mapped[datetime] = mapped_column(default_factory=datetime.utcnow)\r\n \r\n author = relationship('User', back_populates='bookmarks')\r\n post = relationship('Post', back_populates='bookmarks')"}
38
+ {"file_name": "992a1593-7731-43c3-84e3-d0b41fd9e31e.png", "code": "from datetime import datetime\r\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\r\nfrom ..database import Base\r\nfrom sqlalchemy import ForeignKey\r\n\r\n\r\nclass Comment(Base):\r\n __tablename__ = 'comments'\r\n \r\n id: Mapped[str] = mapped_column(primary_key=True)\r\n author_id: Mapped[str] = mapped_column(ForeignKey('users.id'))\r\n post_id: Mapped[str] = mapped_column(ForeignKey('posts.id'))\r\n comment_text: Mapped[str]\r\n comment_date: Mapped[datetime] = mapped_column(default_factory=datetime.utcnow)\r\n \r\n author = relationship('User', back_populates='comments')\r\n post = relationship('Post', back_populates='comments')"}
39
+ {"file_name": "2c1a40c3-6579-4a24-9a78-18274714569b.png", "code": "from datetime import datetime\r\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\r\nfrom ..database import Base\r\nfrom sqlalchemy import ForeignKey\r\n\r\n\r\nclass Like(Base):\r\n __tablename__ = 'likes'\r\n \r\n author_id: Mapped[str] = mapped_column(ForeignKey('users.id'), primary_key=True)\r\n post_id: Mapped[str] = mapped_column(ForeignKey('posts.id'), primary_key=True)\r\n like_date: Mapped[datetime] = mapped_column(default_factory=datetime.utcnow)\r\n \r\n author = relationship('User', back_populates='likes')\r\n post = relationship('Post', back_populates='likes')"}
40
+ {"file_name": "878e2470-d29d-454c-9641-b327191807fb.png", "code": "from datetime import datetime\r\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\r\nfrom sqlalchemy import ForeignKey\r\nfrom ..database import Base\r\n\r\n\r\nclass Post(Base):\r\n __tablename__ = 'posts'\r\n \r\n id: Mapped[str] = mapped_column(primary_key=True)\r\n author_id: Mapped[str] = mapped_column(ForeignKey('users.id'))\r\n location: Mapped[str]\r\n text: Mapped[str]\r\n image_url: Mapped[str]\r\n date_published: Mapped[datetime] = mapped_column(default_factory=datetime.utcnow)\r\n date_updated: Mapped[datetime] = mapped_column(onupdate=datetime.utcnow, default_factory=datetime.utcnow)\r\n \r\n author = relationship('User', back_populates='posts')\r\n bookmarks = relationship('Bookmark', back_populates='post')\r\n likes = relationship('Like', back_populates='post')\r\n comments = relationship('Comment', back_populates='post')\r\n views = relationship('View', back_populates='post')"}
41
+ {"file_name": "8a24871f-5c90-4a39-bdbd-bb012e491e2d.png", "code": "class User(Base):\r\n __tablename__ = 'users'\r\n \r\n id: Mapped[str] = mapped_column(primary_key=True)\r\n first_name: Mapped[str]\r\n last_name: Mapped[str]\r\n email_address: Mapped[str] = mapped_column(unique=True)\r\n password: Mapped[str]\r\n registration_date: Mapped[datetime] = mapped_column(default_factory=datetime.utcnow)\r\n role: Mapped[str] = mapped_column(default='user')\r\n activated: Mapped[bool] = mapped_column(default=False)\r\n profile_picture_url: Mapped[str] = mapped_column(default='default.jpeg')\r\n \r\n posts = relationship('Post', back_populates='author')\r\n bookmarks = relationship('Bookmark', back_populates='author')\r\n likes = relationship('Like', back_populates='author')\r\n comments = relationship('Comment', back_populates='author')\r\n views = relationship('View', back_populates='author')\r\n \r\n @staticmethod\r\n def hash_password(password: str) -> str:\r\n return bcrypt.generate_password_hash(password).decode(\"utf-8\")\r\n\r\n def check_password(self, password: str) -> bool:\r\n return bcrypt.check_password_hash(self.password, password)"}
42
+ {"file_name": "ce911e48-1315-4645-a9b6-52a33bdb475c.png", "code": "@staticmethod\r\n def hash_password(password: str) -> str:\r\n return bcrypt.generate_password_hash(password).decode(\"utf-8\")\r\n\r\n def check_password(self, password: str) -> bool:\r\n return bcrypt.check_password_hash(self.password, password)\r\n \r\n @staticmethod\r\n def encode_auth_token(user_id: int):\r\n try:\r\n payload = {\r\n \"exp\": datetime.utcnow() + timedelta(days=0, hours=2),\r\n \"iat\": datetime.utcnow(),\r\n \"sub\": user_id,\r\n }\r\n return jwt.encode(payload, current_app.config.get(\"SECRET_KEY\"), algorithm=\"HS256\")\r\n except Exception as e:\r\n return e\r\n \r\n @staticmethod\r\n def decode_auth_token(auth_token: str):\r\n try:\r\n payload = jwt.decode(auth_token, current_app.config.get(\"SECRET_KEY\"), algorithms=\"HS256\")\r\n return payload[\"sub\"]\r\n except (ExpiredSignatureError, InvalidTokenError) as e:\r\n raise e"}
43
+ {"file_name": "d5a1df5d-a94b-410b-b2b5-c2b763f8544e.png", "code": "@staticmethod\r\n def hash_password(password: str) -> str:\r\n return bcrypt.generate_password_hash(password).decode(\"utf-8\")\r\n\r\n def check_password(self, password: str) -> bool:\r\n return bcrypt.check_password_hash(self.password, password)\r\n \r\n @staticmethod\r\n def encode_auth_token(user_id: int):\r\n try:\r\n payload = {\r\n \"exp\": datetime.utcnow() + timedelta(days=0, hours=2),\r\n \"iat\": datetime.utcnow(),\r\n \"sub\": user_id,\r\n }\r\n return jwt.encode(payload, current_app.config.get(\"SECRET_KEY\"), algorithm=\"HS256\")\r\n except Exception as e:\r\n return e\r\n \r\n @staticmethod\r\n def decode_auth_token(auth_token: str):\r\n try:\r\n payload = jwt.decode(auth_token, current_app.config.get(\"SECRET_KEY\"), algorithms=\"HS256\")\r\n return payload[\"sub\"]\r\n except (ExpiredSignatureError, InvalidTokenError) as e:\r\n raise e"}
44
+ {"file_name": "0aecb918-dc95-40fe-b10a-6e4c39a730d4.png", "code": "from datetime import datetime\r\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\r\nfrom ..database import Base\r\nfrom sqlalchemy import ForeignKey\r\n\r\n\r\nclass View(Base):\r\n __tablename__ = 'views'\r\n \r\n id: Mapped[str] = mapped_column(primary_key=True)\r\n author_id: Mapped[str] = mapped_column(ForeignKey('users.id'))\r\n post_id: Mapped[str] = mapped_column(ForeignKey('posts.id'))\r\n view_date: Mapped[datetime] = mapped_column(default_factory=datetime.utcnow)\r\n \r\n author = relationship('User', back_populates='views')\r\n post = relationship('Post', back_populates='views')"}
45
+ {"file_name": "e600100c-90f9-4128-b594-4062e6d50670.png", "code": "from pydantic import BaseModel\r\nfrom typing import Optional\r\nfrom datetime import datetime\r\n\r\n\r\nclass CreateActivity(BaseModel):\r\n user_id: str\r\n post_id: str\r\n \r\n\r\nclass ActivityCreated(CreateActivity):\r\n date_created: datetime\r\n \r\nclass RepeatableActivityCreated(ActivityCreated):\r\n id: str\r\n \r\nclass GetRepeatableActivity(BaseModel):\r\n id: str\r\n \r\nclass CreateComment(CreateActivity):\r\n comment: str\r\n \r\nclass CommentCreated(CreateComment):\r\n comment_id: str\r\n date_created: datetime"}
46
+ {"file_name": "2c039ad7-70e8-4ecd-ad69-0dd6713187dc.png", "code": "from pydantic import BaseModel\r\nfrom .post import PostAuthor\r\n \r\nclass CommentSchema(BaseModel):\r\n author: PostAuthor\r\n text: str"}
47
+ {"file_name": "31cc3477-e7a8-4ed0-9004-c52b618822b4.png", "code": "from pydantic import BaseModel, Field\r\nfrom typing import Optional\r\nfrom datetime import datetime\r\n\r\n\r\nclass PostBase(BaseModel):\r\n location: str\r\n text: str\r\n author_id: str\r\n\r\n\r\nclass CreatePost(PostBase):\r\n pass\r\n\r\nclass UpdatePost(BaseModel):\r\n post_id: str\r\n author_id: str\r\n location: Optional[str]\r\n text: Optional[str]\r\n\r\nclass CreatedPost(PostBase):\r\n date_published: datetime\r\n id: str\r\n image_url: str\r\n likes: list\r\n \r\nclass GetPost(BaseModel):\r\n post_id: str"}
48
+ {"file_name": "6ad63eb1-acab-4dac-b73c-6e82790cc44e.png", "code": "class GetPosts(BaseModel):\r\n offset: Optional[int] = 0\r\n limit: Optional[int] = 10\r\n \r\nclass PostAuthor(BaseModel):\r\n id: str\r\n profile_picture: str\r\n name: str\r\n \r\nclass PostLike(BaseModel):\r\n liked: bool\r\n liked_by: Optional[list[PostAuthor]] = Field(default_factory=list)\r\n key_like: Optional[PostAuthor] = None\r\n likes_count: Optional[int] = Field(default=0)\r\n \r\nclass KeyComment(BaseModel):\r\n author: PostAuthor\r\n text: str\r\n comments_count: int\r\n \r\nclass PostSchema(BaseModel):\r\n id: str\r\n text: str\r\n image: str\r\n author: PostAuthor\r\n date_published: str\r\n location: str\r\n like: PostLike\r\n bookmarked: bool\r\n key_comment: Optional[KeyComment] = None"}
49
+ {"file_name": "0eb0fa3c-13a7-4d1a-8c58-20a963a110b8.png", "code": "class GetPosts(BaseModel):\r\n offset: Optional[int] = 0\r\n limit: Optional[int] = 10\r\n \r\nclass PostAuthor(BaseModel):\r\n id: str\r\n profile_picture: str\r\n name: str\r\n \r\nclass PostLike(BaseModel):\r\n liked: bool\r\n liked_by: Optional[list[PostAuthor]] = Field(default_factory=list)\r\n key_like: Optional[PostAuthor] = None\r\n likes_count: Optional[int] = Field(default=0)\r\n \r\nclass KeyComment(BaseModel):\r\n author: PostAuthor\r\n text: str\r\n comments_count: int\r\n \r\nclass PostSchema(BaseModel):\r\n id: str\r\n text: str\r\n image: str\r\n author: PostAuthor\r\n date_published: str\r\n location: str\r\n like: PostLike\r\n bookmarked: bool\r\n key_comment: Optional[KeyComment] = None"}
50
+ {"file_name": "e2e92910-b88e-4cde-9ebd-610b79a35f63.png", "code": "class GetPosts(BaseModel):\r\n offset: Optional[int] = 0\r\n limit: Optional[int] = 10\r\n \r\nclass PostAuthor(BaseModel):\r\n id: str\r\n profile_picture: str\r\n name: str\r\n \r\nclass PostLike(BaseModel):\r\n liked: bool\r\n liked_by: Optional[list[PostAuthor]] = Field(default_factory=list)\r\n key_like: Optional[PostAuthor] = None\r\n likes_count: Optional[int] = Field(default=0)\r\n \r\nclass KeyComment(BaseModel):\r\n author: PostAuthor\r\n text: str\r\n comments_count: int\r\n \r\nclass PostSchema(BaseModel):\r\n id: str\r\n text: str\r\n image: str\r\n author: PostAuthor\r\n date_published: str\r\n location: str\r\n like: PostLike\r\n bookmarked: bool\r\n key_comment: Optional[KeyComment] = None"}
51
+ {"file_name": "2b9c8a78-9e45-4917-836c-74c4d992389d.png", "code": "from pydantic import BaseModel\r\nfrom typing import Optional\r\n\r\n\r\nclass UserBase(BaseModel):\r\n first_name: str\r\n last_name: str\r\n email_address: str\r\n\r\n \r\nclass UserCreate(UserBase):\r\n password: str\r\n role: str = 'user'\r\n activated: bool = False\r\n \r\nclass UserCreated(UserBase):\r\n id: str\r\n activation_token: str\r\n\r\nclass User(UserBase):\r\n id: str\r\n \r\n class Config:\r\n from_attributes = True\r\n \r\nclass GetUser(BaseModel):\r\n user_id: str\r\n \r\nclass GetUsers(BaseModel):\r\n offset: Optional[int] = 0\r\n limit: Optional[int] = 10\r\n \r\nclass ActivateUser(BaseModel):\r\n user_id: str\r\n activation_token: str\r\n \r\nclass LoginUser(BaseModel):\r\n email_address: str\r\n password: str"}
52
+ {"file_name": "9d933d9e-56f5-4a86-a8f4-e4164058b6cc.png", "code": "class LoggedInUser(BaseModel):\r\n email_address: str\r\n access_token: str\r\n refresh_token: str\r\n \r\nclass RequestPasswordReset(BaseModel):\r\n user_id: str\r\n email_address: str\r\n \r\nclass RequestPasswordResetToken(RequestPasswordReset):\r\n password_reset_token: str\r\n \r\nclass PasswordReset(BaseModel):\r\n email_address: str\r\n password_reset_token: str\r\n password: str\r\n confirm_password: str"}
53
+ {"file_name": "ef24c797-843c-48ab-9ebb-98bb4f168daa.png", "code": "from sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import DeclarativeBase, MappedAsDataclass\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom ...config.config import BaseConfig\r\nfrom contextlib import contextmanager\r\nfrom flask import current_app\r\n\r\n\r\nclass Base(MappedAsDataclass, DeclarativeBase):\r\n pass\r\n\r\nSQLALCHEMY_DATABASE_URI = BaseConfig().db_conn_string\r\nengine = create_engine(SQLALCHEMY_DATABASE_URI)\r\nSession = sessionmaker(bind=engine, autocommit=False, autoflush=False)\r\n\r\ndef create_all():\r\n Base.metadata.create_all(bind=engine)\r\n \r\ndef drop_all():\r\n Base.metadata.drop_all(bind=engine)\r\n\r\n@contextmanager\r\ndef get_db():\r\n try:\r\n db = Session()\r\n yield db\r\n finally:\r\n db.close()"}
54
+ {"file_name": "b84b4833-928e-4a28-b5ad-556b2d045a8e.png", "code": "from sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import DeclarativeBase, MappedAsDataclass\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom ...config.config import BaseConfig\r\nfrom contextlib import contextmanager\r\nfrom flask import current_app\r\n\r\n\r\nclass Base(MappedAsDataclass, DeclarativeBase):\r\n pass\r\n\r\nSQLALCHEMY_DATABASE_URI = BaseConfig().db_conn_string\r\nengine = create_engine(SQLALCHEMY_DATABASE_URI)\r\nSession = sessionmaker(bind=engine, autocommit=False, autoflush=False)\r\n\r\ndef create_all():\r\n Base.metadata.create_all(bind=engine)\r\n \r\ndef drop_all():\r\n Base.metadata.drop_all(bind=engine)\r\n\r\n@contextmanager\r\ndef get_db():\r\n try:\r\n db = Session()\r\n yield db\r\n finally:\r\n db.close()"}
55
+ {"file_name": "042b0e58-929d-4d08-90b7-ef6ffd6f00fa.png", "code": "from sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import DeclarativeBase, MappedAsDataclass\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom ...config.config import BaseConfig\r\nfrom contextlib import contextmanager\r\nfrom flask import current_app\r\n\r\n\r\nclass Base(MappedAsDataclass, DeclarativeBase):\r\n pass\r\n\r\nSQLALCHEMY_DATABASE_URI = BaseConfig().db_conn_string\r\nengine = create_engine(SQLALCHEMY_DATABASE_URI)\r\nSession = sessionmaker(bind=engine, autocommit=False, autoflush=False)\r\n\r\ndef create_all():\r\n Base.metadata.create_all(bind=engine)\r\n \r\ndef drop_all():\r\n Base.metadata.drop_all(bind=engine)\r\n\r\n@contextmanager\r\ndef get_db():\r\n try:\r\n db = Session()\r\n yield db\r\n finally:\r\n db.close()"}
56
+ {"file_name": "a7c4375a-4e69-4f0e-b986-a7610255307b.png", "code": "from sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import DeclarativeBase, MappedAsDataclass\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom ...config.config import BaseConfig\r\nfrom contextlib import contextmanager\r\nfrom flask import current_app\r\n\r\n\r\nclass Base(MappedAsDataclass, DeclarativeBase):\r\n pass\r\n\r\nSQLALCHEMY_DATABASE_URI = BaseConfig().db_conn_string\r\nengine = create_engine(SQLALCHEMY_DATABASE_URI)\r\nSession = sessionmaker(bind=engine, autocommit=False, autoflush=False)\r\n\r\ndef create_all():\r\n Base.metadata.create_all(bind=engine)\r\n \r\ndef drop_all():\r\n Base.metadata.drop_all(bind=engine)\r\n\r\n@contextmanager\r\ndef get_db():\r\n try:\r\n db = Session()\r\n yield db\r\n finally:\r\n db.close()"}
57
+ {"file_name": "cb064bdf-6439-4fdd-b85d-85a3cee514ac.png", "code": "from ..database.crud.user import get_random_user\r\nfrom ..database.crud.post import get_posts\r\nfrom ..database.crud.like import list_post_likes, get_key_like, has_liked\r\nfrom ..database.crud.comment import get_key_comment, list_post_comments\r\nfrom ..database.crud.bookmark import has_bookmarked\r\nfrom ..database.database import get_db\r\nfrom ..database.models import (\r\n User, Post, Like, Bookmark, Comment\r\n)\r\nfrom ..database.schemas.post import (\r\n GetPosts, PostAuthor, GetPost, PostLike, KeyComment, PostSchema\r\n)\r\nfrom ..database.schemas.activity import CreateActivity\r\nfrom flask import url_for\r\nfrom pydantic import ValidationError\r\nfrom sqlalchemy.exc import OperationalError, IntegrityError\r\nfrom datetime import datetime"}
58
+ {"file_name": "ba2deb3e-56d9-45fd-9be8-a6b2c0956e69.png", "code": "\"\"\"This module contains routes for the app.\"\"\"\r\nfrom flask import Blueprint, render_template, jsonify, request, url_for\r\nfrom http import HTTPStatus\r\nfrom ..database.schemas.activity import (\r\n ActivityCreated, CreateActivity, RepeatableActivityCreated,\r\n CreateComment, CommentCreated)\r\nfrom ..database.models import (\r\n User, Post, Comment, Bookmark, Like, View\r\n)\r\nfrom ..database.schemas.user import GetUser\r\nfrom ..database.schemas.post import GetPost\r\nfrom ..database.database import get_db\r\nfrom ..database.crud.user import get_user, get_random_user\r\nfrom ..database.crud.post import get_post\r\nfrom ..database.crud.bookmark import (\r\n create_bookmark, delete_bookmark, list_user_bookmarks, has_bookmarked\r\n)\r\nfrom ..database.crud.view import (\r\n create_view, list_user_views, has_viewed\r\n)\r\nfrom ..database.crud.like import (\r\n create_like, delete_like, list_user_likes, has_liked, list_post_likes, \r\n get_key_like\r\n)\r\nfrom ..database.crud.comment import (\r\n create_comment, list_user_comments, list_post_comments\r\n)\r\nfrom pydantic import ValidationError\r\nfrom sqlalchemy.exc import OperationalError, IntegrityError\r\nfrom ..database.schemas.post import (\r\n CreatePost, CreatedPost, GetPost, GetPosts, UpdatePost, PostSchema, PostAuthor, \r\n PostLike, KeyComment\r\n)\r\nfrom ..database.crud.post import (\r\n create_post, get_post, get_posts, delete_post, update_post\r\n)\r\nfrom ..database.crud.comment import get_key_comment"}
59
+ {"file_name": "b1eb25ad-bf1e-4b8b-870b-18948d0a44e7.png", "code": "\"\"\"This module contains routes for the app.\"\"\"\r\nfrom flask import Blueprint, flash, jsonify, redirect, render_template, request, url_for\r\nfrom http import HTTPStatus\r\nfrom ..database.schemas.post import (\r\n CreatePost, CreatedPost, GetPost, GetPosts, UpdatePost, PostSchema, PostAuthor\r\n)\r\nfrom ..database.crud.post import (\r\n create_post, get_post, get_posts, delete_post, update_post\r\n)\r\nfrom ..database.models.post import Post\r\nfrom ..database.database import get_db\r\nfrom pydantic import ValidationError\r\nfrom sqlalchemy.exc import OperationalError, IntegrityError\r\nfrom ..database.models.user import User\r\nfrom ..database.crud.user import get_user\r\nfrom ..database.schemas.user import GetUser\r\nfrom ..database.models.bookmark import Bookmark\r\nfrom ..database.crud.bookmark import list_post_bookmarks\r\nfrom ..database.schemas.activity import ActivityCreated, RepeatableActivityCreated, CommentCreated\r\nfrom ..database.crud.like import list_post_likes\r\nfrom ..database.models.like import Like\r\nfrom ..database.models.comment import Comment\r\nfrom ..database.models.view import View\r\nfrom ..database.schemas.comment import CommentSchema\r\nfrom ..database.crud.view import (\r\n list_post_views\r\n)\r\nfrom ..database.crud.comment import list_post_comments\r\nfrom ..home.helpers import load_posts\r\n\r\npost = Blueprint(\"post\", __name__)"}
60
+ {"file_name": "cc711d16-d41b-44b3-99d1-f8e1215e9a0f.png", "code": "@post.route(\"/create\", methods=[\"POST\", \"GET\"])\r\ndef create_new_post():\r\n \"\"\"Create a new post.\"\"\"\r\n if request.method == 'GET':\r\n return {'success': 'post creation form'}, HTTPStatus.OK\r\n elif request.method == 'POST':\r\n try:\r\n post_data = CreatePost(**request.form) \r\n except ValidationError:\r\n return {'Error': 'The data provided is invalid or incomplete!'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n user_data = GetUser(user_id=post_data.author_id)\r\n user = get_user(session=get_db, user_data=user_data)\r\n if not user:\r\n return {'Error': f'User with id {user_data.user_id} does not exists'}, HTTPStatus.NOT_FOUND \r\n post: Post = create_post(post_data=post_data, post_image=request.files, session=get_db) \r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = CreatedPost(\r\n id=post.id,\r\n location=post.location,\r\n text=post.text,\r\n image_url=post.image_url,\r\n author_id=post.author_id,\r\n date_published=post.date_published\r\n )\r\n return resp.model_dump_json(indent=4), HTTPStatus.CREATED"}
61
+ {"file_name": "24fd00b5-7c78-41e4-8b8b-9dc01a58bb09.png", "code": "@post.route(\"/create\", methods=[\"POST\", \"GET\"])\r\ndef create_new_post():\r\n \"\"\"Create a new post.\"\"\"\r\n if request.method == 'GET':\r\n return {'success': 'post creation form'}, HTTPStatus.OK\r\n elif request.method == 'POST':\r\n try:\r\n post_data = CreatePost(**request.form) \r\n except ValidationError:\r\n return {'Error': 'The data provided is invalid or incomplete!'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n user_data = GetUser(user_id=post_data.author_id)\r\n user = get_user(session=get_db, user_data=user_data)\r\n if not user:\r\n return {'Error': f'User with id {user_data.user_id} does not exists'}, HTTPStatus.NOT_FOUND \r\n post: Post = create_post(post_data=post_data, post_image=request.files, session=get_db) \r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = CreatedPost(\r\n id=post.id,\r\n location=post.location,\r\n text=post.text,\r\n image_url=post.image_url,\r\n author_id=post.author_id,\r\n date_published=post.date_published\r\n )\r\n return resp.model_dump_json(indent=4), HTTPStatus.CREATED"}
62
+ {"file_name": "8a83eada-a368-4ff8-902f-820d7b9a8b4c.png", "code": "@post.route(\"/update\", methods=[\"PUT\"])\r\ndef update_one_post():\r\n \"\"\"Update a post.\"\"\"\r\n if request.method == 'GET':\r\n return {'success': 'post creation form'}, HTTPStatus.OK\r\n elif request.method == 'PUT':\r\n try:\r\n post_data = UpdatePost(\r\n **request.form\r\n )\r\n except ValidationError:\r\n return {'Error': 'The data provided is invalid or incomplete!'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n user_data = GetUser(user_id=post_data.author_id)\r\n user: User = get_user(session=get_db, user_data=user_data)\r\n if not user:\r\n return {'Error': f'User with id {user_data.user_id} does not exists'}, HTTPStatus.NOT_FOUND \r\n post: Post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n if user.id != post.author_id:\r\n return {'Error': 'You can only update your own post!'}, HTTPStatus.FORBIDDEN\r\n post: Post = update_post(post_data=post_data, post_image=request.files, session=get_db) \r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = CreatedPost(\r\n id=post.id,\r\n location=post.location,\r\n text=post.text,\r\n image_url=post.image_url,\r\n author_id=post.author_id,\r\n date_published=post.date_published\r\n )\r\n return resp.model_dump_json(indent=4), HTTPStatus.CREATED"}
63
+ {"file_name": "c2dc3c16-ad06-4188-a9b0-351b4809ebaf.png", "code": "@post.route(\"/delete\", methods=[\"DELETE\"])\r\ndef delete_one_post():\r\n \"\"\"Delete a post.\"\"\"\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n post = delete_post(get_db, GetPost(post_id=request.args.get('post_id')))\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = CreatedPost(\r\n id=post.id,\r\n location=post.location,\r\n text=post.text,\r\n image_url=post.image_url,\r\n author_id=post.author_id,\r\n date_published=post.date_published\r\n )\r\n return resp.model_dump_json(indent=4), HTTPStatus.OK"}
64
+ {"file_name": "433ad831-76e2-4645-983c-f73639f14809.png", "code": "@post.route(\"/get\", methods=[\"GET\"])\r\ndef get_one_post():\r\n \"\"\"Get a single post.\"\"\"\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post = get_post(session=get_db, post_data=post_data)\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n if post:\r\n resp = CreatedPost(\r\n id=post.id,\r\n location=post.location,\r\n text=post.text,\r\n image_url=post.image_url,\r\n author_id=post.author_id,\r\n date_published=post.date_published\r\n )\r\n return resp.model_dump_json(indent=4), HTTPStatus.OK\r\n \r\n return {'Error':f'No post with id {post_data.post_id}'}, HTTPStatus.NOT_FOUND"}
65
+ {"file_name": "e5d2caf4-eb4f-45f5-87d7-57765e86ee03.png", "code": "@post.route(\"/posts\", methods=[\"GET\"])\r\ndef get_all_posts():\r\n \"\"\"Get many post post.\"\"\"\r\n offset: str = request.args.get('offset')\r\n limit: str = request.args.get('limit')\r\n try:\r\n posts = get_posts(get_db, GetPosts(offset=offset, limit=limit))\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n created_posts = []\r\n for post in posts:\r\n post_author: PostAuthor = PostAuthor(\r\n id=post.author.id,\r\n profile_picture=url_for('static', filename='img/default.jpeg'),\r\n name=post.author.first_name\r\n )\r\n post_schema: PostSchema = PostSchema(\r\n id=post.id,\r\n text=post.text,\r\n image=url_for('static', filename=f'img/{post.image_url}'),\r\n location=post.location,\r\n date_published='10',\r\n author=post_author\r\n ).model_dump()\r\n created_posts.append(post_schema)"}
66
+ {"file_name": "eb539461-d0c9-4cc4-88bc-660ca0f77eb4.png", "code": "# posts = [\r\n # CreatedPost(\r\n # id=post.id,\r\n # location=post.location,\r\n # text=post.text,\r\n # image_url=post.image_url,\r\n # author_id=post.author_id,\r\n # date_published=post.date_published\r\n # ).model_dump()\r\n # for post in posts\r\n # ]\r\n return created_posts, HTTPStatus.OK\r\n\r\[email protected](\"/load_more_posts\", methods=[\"GET\"])\r\ndef load_more_posts():\r\n \"\"\"Get a single post.\"\"\"\r\n offset: str = request.args.get('offset', 0)\r\n limit: str = request.args.get('limit', 10)\r\n more_posts = load_posts(limit=int(limit), offset=int(offset))\r\n return more_posts"}
67
+ {"file_name": "f7541013-5bde-485c-a9ff-e8749f8908b7.png", "code": "# posts = [\r\n # CreatedPost(\r\n # id=post.id,\r\n # location=post.location,\r\n # text=post.text,\r\n # image_url=post.image_url,\r\n # author_id=post.author_id,\r\n # date_published=post.date_published\r\n # ).model_dump()\r\n # for post in posts\r\n # ]\r\n return created_posts, HTTPStatus.OK\r\n\r\[email protected](\"/load_more_posts\", methods=[\"GET\"])\r\ndef load_more_posts():\r\n \"\"\"Get a single post.\"\"\"\r\n offset: str = request.args.get('offset', 0)\r\n limit: str = request.args.get('limit', 10)\r\n more_posts = load_posts(limit=int(limit), offset=int(offset))\r\n return more_posts"}
68
+ {"file_name": "933ed423-6f8b-4a99-90f4-c427d7245c0d.png", "code": "@post.route(\"/load_more_comments\", methods=[\"GET\"])\r\ndef load_more_comments():\r\n \"\"\"Get a single post.\"\"\"\r\n offset: str = request.args.get('offset', 0)\r\n limit: str = request.args.get('limit', 10)\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post: Post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n comments: list[Comment] = list_post_comments(session=get_db, post_data=post_data, offset=offset, limit=limit)\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n post_comments = []\r\n for comment in comments:\r\n comment_author: PostAuthor = PostAuthor(\r\n id=comment.author.id,\r\n profile_picture=url_for('static', filename=f'img/{comment.author.profile_picture_url}'),\r\n name=comment.author.first_name\r\n )\r\n comment_schema: CommentSchema = CommentSchema(\r\n author=comment_author,\r\n text=comment.comment_text\r\n )\r\n post_comments.append(comment_schema.model_dump())\r\n return post_comments"}
69
+ {"file_name": "5970340c-dd8c-4354-9ea8-c3f0cdc63db6.png", "code": "@post.route(\"/load_more_comments\", methods=[\"GET\"])\r\ndef load_more_comments():\r\n \"\"\"Get a single post.\"\"\"\r\n offset: str = request.args.get('offset', 0)\r\n limit: str = request.args.get('limit', 10)\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post: Post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n comments: list[Comment] = list_post_comments(session=get_db, post_data=post_data, offset=offset, limit=limit)\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n post_comments = []\r\n for comment in comments:\r\n comment_author: PostAuthor = PostAuthor(\r\n id=comment.author.id,\r\n profile_picture=url_for('static', filename=f'img/{comment.author.profile_picture_url}'),\r\n name=comment.author.first_name\r\n )\r\n comment_schema: CommentSchema = CommentSchema(\r\n author=comment_author,\r\n text=comment.comment_text\r\n )\r\n post_comments.append(comment_schema.model_dump())\r\n return post_comments"}
70
+ {"file_name": "41912548-ff7c-4d8f-9460-4dd10ff66cbb.png", "code": "@post.route(\"/likes\", methods=[\"GET\"])\r\ndef get_post_likes():\r\n \"\"\"Get a posts likes.\"\"\"\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post: Post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n likes: list[Bookmark] = list_post_likes(session=get_db, post_data=post_data)\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = [\r\n ActivityCreated(\r\n user_id=like.author_id,\r\n post_id=like.post_id,\r\n date_created=like.like_date\r\n ).model_dump()\r\n for like in likes\r\n ]\r\n return resp, HTTPStatus.OK"}
71
+ {"file_name": "d1178954-f79b-416f-870b-617b834f43e5.png", "code": "@post.route(\"/likes\", methods=[\"GET\"])\r\ndef get_post_likes():\r\n \"\"\"Get a posts likes.\"\"\"\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post: Post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n likes: list[Bookmark] = list_post_likes(session=get_db, post_data=post_data)\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = [\r\n ActivityCreated(\r\n user_id=like.author_id,\r\n post_id=like.post_id,\r\n date_created=like.like_date\r\n ).model_dump()\r\n for like in likes\r\n ]\r\n return resp, HTTPStatus.OK"}
72
+ {"file_name": "ecf7e69b-799a-4042-8819-c23f04b73835.png", "code": "@post.route(\"/bookmarks\", methods=[\"GET\"])\r\ndef get_post_bookmarks():\r\n \"\"\"Bookmark a single post.\"\"\"\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post: Post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n bookmarks: list[Bookmark] = list_post_bookmarks(session=get_db, post_data=post_data)\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = [\r\n ActivityCreated(\r\n user_id=bookmark.author_id,\r\n post_id=bookmark.post_id,\r\n date_created=bookmark.bookmark_date\r\n ).model_dump()\r\n for bookmark in bookmarks\r\n ]\r\n return resp, HTTPStatus.OK"}
73
+ {"file_name": "f71cfa41-9cc5-471b-902b-bb69c4c8c341.png", "code": "@post.route(\"/comments\", methods=[\"GET\"])\r\ndef get_post_comments():\r\n \"\"\"Get a posts comments.\"\"\"\r\n offset: str = request.args.get('offset', 0)\r\n limit: str = request.args.get('limit', 10)\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post: Post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n comments: list[Comment] = list_post_comments(session=get_db, post_data=post_data, offset=offset, limit=limit)\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = [\r\n CommentCreated(\r\n user_id=comment.author_id,\r\n post_id=comment.post_id,\r\n date_created=comment.comment_date,\r\n comment_id=comment.id,\r\n comment=comment.comment_text\r\n ).model_dump()\r\n for comment in comments\r\n ]\r\n return resp, HTTPStatus.OK"}
74
+ {"file_name": "21d5bfe5-5d49-4ff4-9425-6126cb42cd6b.png", "code": "@post.route(\"/views\", methods=[\"GET\"])\r\ndef get_post_views():\r\n \"\"\"Get a posts comments.\"\"\"\r\n try:\r\n post_data = GetPost(post_id=request.args.get('post_id'))\r\n except ValidationError:\r\n return {'error': 'Invalid input: you probably did not include the post id.'}, HTTPStatus.BAD_REQUEST\r\n try:\r\n post: Post = get_post(session=get_db, post_data=post_data)\r\n if not post:\r\n return {'Error': f'post with id {post_data.post_id} does not exists'}, HTTPStatus.NOT_FOUND\r\n views: list[View] = list_post_views(session=get_db, post_data=post_data)\r\n except (OperationalError, IntegrityError) as e:\r\n print(e)\r\n # Send email to\r\n return {'Error': 'The application is experiencing a tempoary error. Please try again in a few minutes.'}, HTTPStatus.INTERNAL_SERVER_ERROR\r\n resp = [\r\n RepeatableActivityCreated(\r\n user_id=view.author_id,\r\n post_id=view.post_id,\r\n date_created=view.view_date,\r\n id=view.id\r\n ).model_dump()\r\n for view in views\r\n ]\r\n return resp, HTTPStatus.OK"}
75
+ {"file_name": "8bc4fdf5-017b-471c-896f-4a79a708acdb.png", "code": "\"\"\"This module declares the app configuration.\r\n\r\nThe classes include:\r\n\r\nBaseConfig:\r\n Has all the configurations shared by all the environments.\r\n\r\n\"\"\"\r\nimport os\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\n\r\nclass BaseConfig:\r\n \"\"\"Base configuration.\"\"\"\r\n\r\n DEBUG = True\r\n TESTING = False\r\n SECRET_KEY = os.environ[\"SECRET_KEY\"]\r\n db_conn_string = 'sqlite:///./butterfly.db'\r\n SQLALCHEMY_DATABASE_URI = db_conn_string\r\n SQLALCHEMY_TRACK_MODIFICATIONS = False"}
76
+ {"file_name": "c795b855-cc1e-4937-b1a9-38efcbf970c2.png", "code": "\"\"\"This module declares the app configuration.\r\n\r\nThe classes include:\r\n\r\nBaseConfig:\r\n Has all the configurations shared by all the environments.\r\n\r\n\"\"\"\r\nimport os\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\n\r\nclass BaseConfig:\r\n \"\"\"Base configuration.\"\"\"\r\n\r\n DEBUG = True\r\n TESTING = False\r\n SECRET_KEY = os.environ[\"SECRET_KEY\"]\r\n db_conn_string = 'sqlite:///./butterfly.db'\r\n SQLALCHEMY_DATABASE_URI = db_conn_string\r\n SQLALCHEMY_TRACK_MODIFICATIONS = False"}
77
+ {"file_name": "6a9f4dcc-adae-473c-ad12-8e679a5abae0.png", "code": "class DevelopmentConfig(BaseConfig):\r\n \"\"\"Development confuguration.\"\"\"\r\n\r\n DEBUG = True\r\n TESTING = False\r\n \r\n\r\nclass TestingConfig(BaseConfig):\r\n \"\"\"Testing configuration.\"\"\"\r\n\r\n TESTING = True\r\n SECRET_KEY = 'secret-key'\r\n SQLALCHEMY_DATABASE_URI = 'sqlite:///'\r\n\r\nclass ProductionConfig(BaseConfig):\r\n \"\"\"Production configuration.\"\"\"\r\n\r\n TESTING = False\r\n\r\n\r\nConfig = {\r\n \"development\": DevelopmentConfig,\r\n \"test\": TestingConfig,\r\n \"production\": ProductionConfig,\r\n \"staging\": ProductionConfig,\r\n}"}
78
+ {"file_name": "953e57d6-3b1c-40b1-a86d-912abadb7092.png", "code": "import logging.config\r\nimport logstash\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\n\r\ndef create_dev_logger():\r\n \"\"\"Create the application logger.\"\"\"\r\n config = {\r\n \"version\": 1,\r\n \"disable_existing_loggers\": False,\r\n \"formatters\": {\r\n \"standard\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n },\r\n \"json\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n \"class\": \"pythonjsonlogger.jsonlogger.JsonFormatter\",\r\n },\r\n },\r\n \"handlers\": {\r\n \"standard\": {\r\n \"class\": \"logging.StreamHandler\",\r\n \"formatter\": \"json\",\r\n },\r\n },\r\n \"loggers\": {\"\": {\"handlers\": [\"standard\"], \"level\": logging.INFO}},\r\n }\r\n\r\n logging.config.dictConfig(config)\r\n\r\n logger = logging.getLogger(__name__)\r\n\r\n return logger"}
79
+ {"file_name": "e3444294-c297-4ca0-b245-0b7484961111.png", "code": "import logging.config\r\nimport logstash\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\n\r\ndef create_dev_logger():\r\n \"\"\"Create the application logger.\"\"\"\r\n config = {\r\n \"version\": 1,\r\n \"disable_existing_loggers\": False,\r\n \"formatters\": {\r\n \"standard\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n },\r\n \"json\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n \"class\": \"pythonjsonlogger.jsonlogger.JsonFormatter\",\r\n },\r\n },\r\n \"handlers\": {\r\n \"standard\": {\r\n \"class\": \"logging.StreamHandler\",\r\n \"formatter\": \"json\",\r\n },\r\n },\r\n \"loggers\": {\"\": {\"handlers\": [\"standard\"], \"level\": logging.INFO}},\r\n }\r\n\r\n logging.config.dictConfig(config)\r\n\r\n logger = logging.getLogger(__name__)\r\n\r\n return logger"}
80
+ {"file_name": "3b2197bd-f36b-4499-b7a7-4f907764e535.png", "code": "import logging.config\r\nimport logstash\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\n\r\ndef create_dev_logger():\r\n \"\"\"Create the application logger.\"\"\"\r\n config = {\r\n \"version\": 1,\r\n \"disable_existing_loggers\": False,\r\n \"formatters\": {\r\n \"standard\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n },\r\n \"json\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n \"class\": \"pythonjsonlogger.jsonlogger.JsonFormatter\",\r\n },\r\n },\r\n \"handlers\": {\r\n \"standard\": {\r\n \"class\": \"logging.StreamHandler\",\r\n \"formatter\": \"json\",\r\n },\r\n },\r\n \"loggers\": {\"\": {\"handlers\": [\"standard\"], \"level\": logging.INFO}},\r\n }\r\n\r\n logging.config.dictConfig(config)\r\n\r\n logger = logging.getLogger(__name__)\r\n\r\n return logger"}
81
+ {"file_name": "99ed9265-42dd-48f6-937c-3a6c3174555f.png", "code": "import logging.config\r\nimport logstash\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\n\r\ndef create_dev_logger():\r\n \"\"\"Create the application logger.\"\"\"\r\n config = {\r\n \"version\": 1,\r\n \"disable_existing_loggers\": False,\r\n \"formatters\": {\r\n \"standard\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n },\r\n \"json\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n \"class\": \"pythonjsonlogger.jsonlogger.JsonFormatter\",\r\n },\r\n },\r\n \"handlers\": {\r\n \"standard\": {\r\n \"class\": \"logging.StreamHandler\",\r\n \"formatter\": \"json\",\r\n },\r\n },\r\n \"loggers\": {\"\": {\"handlers\": [\"standard\"], \"level\": logging.INFO}},\r\n }\r\n\r\n logging.config.dictConfig(config)\r\n\r\n logger = logging.getLogger(__name__)\r\n\r\n return logger"}
82
+ {"file_name": "67276fad-7ece-4f53-9426-c3c4758ba2a2.png", "code": "def create_prod_logger():\r\n \"\"\"Create the application logger.\"\"\"\r\n config = {\r\n \"version\": 1,\r\n \"disable_existing_loggers\": False,\r\n \"formatters\": {\r\n \"standard\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n },\r\n \"json\": {\r\n \"format\": \"%(asctime)s %(name)s %(levelname)s %(message)s\",\r\n \"datefmt\": \"%Y-%m-%dT%H:%M:%S%z\",\r\n \"class\": \"pythonjsonlogger.jsonlogger.JsonFormatter\",\r\n },\r\n },\r\n \"handlers\": {\r\n \"standard\": {\r\n \"class\": \"logging.StreamHandler\",\r\n \"formatter\": \"json\",\r\n },\r\n },\r\n \"loggers\": {\"\": {\"handlers\": [\"standard\"], \"level\": logging.INFO}},\r\n }\r\n\r\n logging.config.dictConfig(config)\r\n\r\n logger = logging.getLogger(__name__)\r\n\r\n return logger"}
83
+ {"file_name": "8f577296-b627-489d-8e0f-8927f93f768f.png", "code": "def create_logger(env=\"development\"):\r\n app_logger = create_dev_logger()\r\n if env == \"production\":\r\n app_logger = create_prod_logger()\r\n return app_logger\r\n\r\n\r\napp_logger = create_logger()\r\napp_logger.addHandler(logstash.TCPLogstashHandler(host='localhost', port=5959, version=1))"}
84
+ {"file_name": "6d39d43f-4664-4ccb-b51e-170c9209a083.png", "code": "\"\"\"This script contains helper methods for use with the application.\"\"\"\r\nfrom flask import Flask\r\n\r\nfrom .config import Config\r\n\r\n\r\ndef set_configuration(app: Flask, flask_env: str = \"development\") -> None:\r\n \"\"\"Set the application configuration.\r\n\r\n The application configuration will depend on the\r\n environment i.e Test, Development, Staging or Production.\r\n\r\n Parameters\r\n ----------\r\n app: flask.Flask\r\n A flask app instance.\r\n \"\"\"\r\n app.config.from_object(Config[flask_env])"}
85
+ {"file_name": "4406b6b3-c17e-4b9c-bc6f-ff9359498875.png", "code": "from flask_bcrypt import Bcrypt\r\nfrom flask_cors import CORS\r\n\r\n\r\nbcrypt = Bcrypt()\r\ncors = CORS()"}
86
+ {"file_name": "87cc57cd-3038-4b45-bc0c-5e4f54c15cfe.png", "code": "\"\"\"This module resgisters the application extensions.\r\n\r\nExample:\r\n To register the extensions:\r\n register_extensions(app)\r\n\r\n@Author: Lyle Okoth\r\n@Date: 28/06/2023\r\n@Portfolio: https://lyleokoth.oryks-sytem.com\r\n\"\"\"\r\nfrom flask import Flask\r\n\r\nfrom .extensions import bcrypt, cors\r\n\r\n\r\ndef register_extensions(app: Flask) -> None:\r\n \"\"\"Register the application extensions.\r\n\r\n Parameters\r\n ----------\r\n app: flask.Flask\r\n The Flask app instance.\r\n \"\"\"\r\n bcrypt.init_app(app)\r\n cors.init_app(app)"}
87
+ {"file_name": "64091096-90d9-4bf4-96b5-4bac075965a3.png", "code": "from ..blueprints.database.schemas.user import UserCreate\r\nfrom ..blueprints.database.schemas.post import CreatePost\r\nfrom ..blueprints.database.models import User, Post, Like, Comment, Bookmark\r\nfrom ..blueprints.database.database import get_db\r\nfrom ..blueprints.database.crud.user import create_user\r\nfrom ..blueprints.database.crud.post import create_post\r\nfrom faker import Faker\r\nfrom datetime import datetime, timedelta\r\nimport random\r\nfrom uuid import uuid4\r\n\r\n\r\nfake = Faker()"}
88
+ {"file_name": "58042b46-df0a-48d2-9d05-c884835b62a2.png", "code": "def generate_users(count: int = 10) -> list[UserCreate]:\r\n \"\"\"Generate ten random users.\"\"\"\r\n first_names = (fake.name() for _ in range(count))\r\n last_names = (fake.name() for _ in range(count))\r\n emails = (fake.email() for i in range(count))\r\n profile_pictures = [f'profile-{i}.jpg' for i in range(21)]\r\n return [\r\n User(\r\n id='User_' + str(uuid4()),\r\n first_name=first_name,\r\n last_name=last_name,\r\n email_address=email,\r\n password=User.hash_password('password'),\r\n profile_picture_url=image\r\n ) \r\n for first_name, last_name, email, image in zip(first_names, last_names, emails, profile_pictures)\r\n ]"}
89
+ {"file_name": "c1c813fa-bcd1-4d43-845d-44f92a39fae6.png", "code": "def generate_posts(authors: list[User], count: int = 100) -> list[Post]:\r\n \"\"\"Generate posts.\"\"\"\r\n cities = [fake.city() for _ in range(10)]\r\n posts_text = [fake.text() for _ in range(count)]\r\n dates_published = (datetime.now() + timedelta(minutes=random.randint(1,60)) for _ in range(count))\r\n post_images = [f'feed-{i}.jpg' for i in range(1,8)]\r\n return [\r\n Post(\r\n id='Post_' + str(uuid4()),\r\n author_id=random.choice(authors).id,\r\n location=random.choice(cities),\r\n text=text,\r\n image_url=random.choice(post_images),\r\n date_published=d\r\n )\r\n for text, d in zip(posts_text, dates_published)\r\n ]\r\n \r\ndef generate_likes(users: list[User], posts: list[Post], likes_count: int = 100) -> list[Like]:\r\n \"\"\"Generate likes.\"\"\"\r\n likes: list[Like] = []\r\n ids = set()\r\n for _ in range(likes_count):\r\n author_id: str = random.choice(users).id\r\n post_id: str = random.choice(posts).id\r\n like: Like = Like(author_id=author_id, post_id=post_id)\r\n if (author_id, post_id) not in ids:\r\n likes.append(like)\r\n ids.add((author_id, post_id))\r\n return likes"}
90
+ {"file_name": "346db193-43af-4288-9434-37c1d0327fb9.png", "code": "ef generate_bookmarks(users: list[User], posts: list[Post], bookmarks_count: int = 100) -> list[Bookmark]:\r\n \"\"\"Generate bookmarks.\"\"\"\r\n bookmarks: list[Bookmark] = []\r\n ids = set()\r\n for _ in range(bookmarks_count):\r\n author_id: str = random.choice(users).id\r\n post_id: str = random.choice(posts).id\r\n bookmark: bookmark = Bookmark(author_id=author_id, post_id=post_id)\r\n if (author_id, post_id) not in ids:\r\n bookmarks.append(bookmark)\r\n ids.add((author_id, post_id))\r\n return bookmarks\r\n\r\ndef generate_comments(users: list[User], posts: list[Post], comments_count: int = 500) -> list[Like]:\r\n \"\"\"Generate likes.\"\"\"\r\n comments: list[Comment] = []\r\n ids = set()\r\n for _ in range(comments_count):\r\n author_id: str = random.choice(users).id\r\n post_id: str = random.choice(posts).id\r\n comment: comment = Comment(\r\n id='Comment_' + str(uuid4()),\r\n author_id=author_id, \r\n post_id=post_id, \r\n comment_text=fake.text() )\r\n if (author_id, post_id) not in ids:\r\n comments.append(comment)\r\n ids.add((author_id, post_id))\r\n return comments"}
91
+ {"file_name": "02edbb24-36ac-4b3a-b344-31c1f26d198b.png", "code": "ef generate_bookmarks(users: list[User], posts: list[Post], bookmarks_count: int = 100) -> list[Bookmark]:\r\n \"\"\"Generate bookmarks.\"\"\"\r\n bookmarks: list[Bookmark] = []\r\n ids = set()\r\n for _ in range(bookmarks_count):\r\n author_id: str = random.choice(users).id\r\n post_id: str = random.choice(posts).id\r\n bookmark: bookmark = Bookmark(author_id=author_id, post_id=post_id)\r\n if (author_id, post_id) not in ids:\r\n bookmarks.append(bookmark)\r\n ids.add((author_id, post_id))\r\n return bookmarks\r\n\r\ndef generate_comments(users: list[User], posts: list[Post], comments_count: int = 500) -> list[Like]:\r\n \"\"\"Generate likes.\"\"\"\r\n comments: list[Comment] = []\r\n ids = set()\r\n for _ in range(comments_count):\r\n author_id: str = random.choice(users).id\r\n post_id: str = random.choice(posts).id\r\n comment: comment = Comment(\r\n id='Comment_' + str(uuid4()),\r\n author_id=author_id, \r\n post_id=post_id, \r\n comment_text=fake.text() )\r\n if (author_id, post_id) not in ids:\r\n comments.append(comment)\r\n ids.add((author_id, post_id))\r\n return comments"}
92
+ {"file_name": "311cefe0-89cf-4f21-a6c0-d3150a24b58b.png", "code": "ef generate_bookmarks(users: list[User], posts: list[Post], bookmarks_count: int = 100) -> list[Bookmark]:\r\n \"\"\"Generate bookmarks.\"\"\"\r\n bookmarks: list[Bookmark] = []\r\n ids = set()\r\n for _ in range(bookmarks_count):\r\n author_id: str = random.choice(users).id\r\n post_id: str = random.choice(posts).id\r\n bookmark: bookmark = Bookmark(author_id=author_id, post_id=post_id)\r\n if (author_id, post_id) not in ids:\r\n bookmarks.append(bookmark)\r\n ids.add((author_id, post_id))\r\n return bookmarks\r\n\r\ndef generate_comments(users: list[User], posts: list[Post], comments_count: int = 500) -> list[Like]:\r\n \"\"\"Generate likes.\"\"\"\r\n comments: list[Comment] = []\r\n ids = set()\r\n for _ in range(comments_count):\r\n author_id: str = random.choice(users).id\r\n post_id: str = random.choice(posts).id\r\n comment: comment = Comment(\r\n id='Comment_' + str(uuid4()),\r\n author_id=author_id, \r\n post_id=post_id, \r\n comment_text=fake.text() )\r\n if (author_id, post_id) not in ids:\r\n comments.append(comment)\r\n ids.add((author_id, post_id))\r\n return comments"}
93
+ {"file_name": "96d9bd34-5f4e-41f2-b115-1bc1951b9a62.png", "code": "def add_user(user: User) -> User:\r\n with get_db() as session:\r\n session.add(user)\r\n session.commit()\r\n session.refresh(user)\r\n return user\r\n\r\ndef add_post(post: Post) -> Post:\r\n with get_db() as session:\r\n session.add(post)\r\n session.commit()\r\n session.refresh(post)\r\n return post\r\n\r\ndef add_likes(likes: list[Like]) -> None:\r\n with get_db() as session:\r\n for like in likes:\r\n session.add(like)\r\n session.commit()\r\n \r\ndef add_bookmarks(bookmarks: list[Bookmark]) -> None:\r\n with get_db() as session:\r\n for bookmark in bookmarks:\r\n session.add(bookmark)\r\n session.commit()\r\n \r\ndef add_comments(comments: list[Comment]) -> None:\r\n with get_db() as session:\r\n for comment in comments:\r\n session.add(comment)\r\n session.commit()"}
94
+ {"file_name": "5a505a2c-0925-456f-99a6-7da1d8e7acfa.png", "code": "def add_user(user: User) -> User:\r\n with get_db() as session:\r\n session.add(user)\r\n session.commit()\r\n session.refresh(user)\r\n return user\r\n\r\ndef add_post(post: Post) -> Post:\r\n with get_db() as session:\r\n session.add(post)\r\n session.commit()\r\n session.refresh(post)\r\n return post\r\n\r\ndef add_likes(likes: list[Like]) -> None:\r\n with get_db() as session:\r\n for like in likes:\r\n session.add(like)\r\n session.commit()\r\n \r\ndef add_bookmarks(bookmarks: list[Bookmark]) -> None:\r\n with get_db() as session:\r\n for bookmark in bookmarks:\r\n session.add(bookmark)\r\n session.commit()\r\n \r\ndef add_comments(comments: list[Comment]) -> None:\r\n with get_db() as session:\r\n for comment in comments:\r\n session.add(comment)\r\n session.commit()"}
95
+ {"file_name": "dfe08b85-dceb-4127-8d07-7e4b994432b7.png", "code": "def generate_data(\r\n user_count: int = 200, \r\n posts_count: int = 500, \r\n likes_count: int = 2000, \r\n comments_count: int = 1000,\r\n bookmarks_count: int = 1500\r\n ):\r\n users = generate_users(user_count)\r\n users = [\r\n add_user(user) for user in users\r\n ]\r\n posts: list[Post] = generate_posts(users, count=posts_count)\r\n posts: list[Post] = [\r\n add_post(post) for post in posts\r\n ]\r\n likes: list[Like] = generate_likes(users, posts, likes_count=likes_count)\r\n add_likes(likes)\r\n \r\n comments: list[Comment] = generate_comments(users, posts, comments_count=comments_count)\r\n add_comments(comments)\r\n \r\n bookmarks: list[Bookmark] = generate_bookmarks(users, posts, bookmarks_count=bookmarks_count)\r\n add_bookmarks(bookmarks)"}
96
+ {"file_name": "8c3195fd-1959-4f06-9fd3-57964694a7c4.png", "code": "from http import HTTPStatus\r\n\r\nfrom flask import Flask, Response, jsonify, make_response\r\n\r\n\r\ndef handle_resource_not_found(exeption: Exception) -> Response:\r\n \"\"\"Handle all resource not found errors.\r\n\r\n Called when an requested resource is not found on the server.\r\n\r\n Parameters\r\n ----------\r\n exception: Exception\r\n The exception that was raised. This is a subclass of Exception.\r\n\r\n Returns\r\n -------\r\n Response:\r\n A string consiting of json data and response code.\r\n \"\"\"\r\n return make_response(jsonify({\"error\": str(exeption)}), HTTPStatus.NOT_FOUND)"}
97
+ {"file_name": "45bf1cbf-a25c-43ff-96a7-3347f1dc8a6f.png", "code": "def handle_method_not_allowed(exeption: Exception) -> Response:\r\n \"\"\"Handle all method not allowed errors.\r\n\r\n Called when a route tries to handle a request with a methods that is not\r\n allowed for the given route.\r\n\r\n Parameters\r\n ----------\r\n exception: Exception\r\n The exception that was raised. This is a subclass of Exception.\r\n\r\n Returns\r\n -------\r\n Response:\r\n A string consiting of json data and response code.\r\n \"\"\"\r\n return make_response(jsonify({\"error\": str(exeption)}), HTTPStatus.METHOD_NOT_ALLOWED)\r\n\r\n\r\ndef handle_internal_server_error(exeption: Exception) -> Response:\r\n \"\"\"Handle all internal server errors.\r\n\r\n This method is called when an error occurs within the application server.\r\n\r\n Parameters\r\n ----------\r\n exception: Exception\r\n The exception that was raised. This is a subclass of Exception.\r\n\r\n Returns\r\n -------\r\n Response:\r\n A string consiting of json data and response code.\r\n \"\"\"\r\n return make_response(jsonify({\"error\": str(exeption)}), HTTPStatus.INTERNAL_SERVER_ERROR)"}
98
+ {"file_name": "ffa478d8-72f1-49ab-8c12-724b032079c3.png", "code": "def handle_unsupported_media_type(exeption: Exception) -> Response:\r\n \"\"\"Handle all unsupported media type errors.\r\n\r\n This method is called when a a request does not supply the data or the data supplied is\r\n invalid.\r\n\r\n Parameters\r\n ----------\r\n exception: Exception\r\n The exception that was raised. This is a subclass of Exception.\r\n\r\n Returns\r\n -------\r\n Response:\r\n A string consiting of json data and response code.\r\n \"\"\"\r\n return make_response(jsonify({\"error\": str(exeption)}), HTTPStatus.UNSUPPORTED_MEDIA_TYPE)\r\n\r\n\r\ndef register_error_handlers(app: Flask) -> None:\r\n \"\"\"Register the error handlers.\r\n\r\n Parameters\r\n ----------\r\n app: flask.Flask\r\n The Flask app instance.\r\n \"\"\"\r\n app.register_error_handler(HTTPStatus.NOT_FOUND, handle_resource_not_found)\r\n app.register_error_handler(HTTPStatus.METHOD_NOT_ALLOWED, handle_method_not_allowed)\r\n app.register_error_handler(HTTPStatus.INTERNAL_SERVER_ERROR, handle_internal_server_error)\r\n app.register_error_handler(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, handle_unsupported_media_type)"}
99
+ {"file_name": "d082f4e2-f1b6-45e6-a323-6667c19eb97f.png", "code": "def handle_unsupported_media_type(exeption: Exception) -> Response:\r\n \"\"\"Handle all unsupported media type errors.\r\n\r\n This method is called when a a request does not supply the data or the data supplied is\r\n invalid.\r\n\r\n Parameters\r\n ----------\r\n exception: Exception\r\n The exception that was raised. This is a subclass of Exception.\r\n\r\n Returns\r\n -------\r\n Response:\r\n A string consiting of json data and response code.\r\n \"\"\"\r\n return make_response(jsonify({\"error\": str(exeption)}), HTTPStatus.UNSUPPORTED_MEDIA_TYPE)\r\n\r\n\r\ndef register_error_handlers(app: Flask) -> None:\r\n \"\"\"Register the error handlers.\r\n\r\n Parameters\r\n ----------\r\n app: flask.Flask\r\n The Flask app instance.\r\n \"\"\"\r\n app.register_error_handler(HTTPStatus.NOT_FOUND, handle_resource_not_found)\r\n app.register_error_handler(HTTPStatus.METHOD_NOT_ALLOWED, handle_method_not_allowed)\r\n app.register_error_handler(HTTPStatus.INTERNAL_SERVER_ERROR, handle_internal_server_error)\r\n app.register_error_handler(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, handle_unsupported_media_type)"}
100
+ {"file_name": "fc9c5d3e-fc14-48a9-9a81-f2e691fd45ee.png", "code": "import json\r\n\r\nfrom flask import request, Flask\r\n\r\nfrom ..config.logger_config import app_logger\r\nfrom .rate_limiter import request_is_rate_limited\r\nfrom redis import Redis\r\nfrom datetime import timedelta\r\nfrom http import HTTPStatus\r\n\r\nr = Redis(host='localhost', port=6379, db=0)\r\n\r\n\r\ndef log_post_request():\r\n request_data = {\r\n \"method\": request.method,\r\n \"url root\": request.url_root,\r\n \"user agent\": request.user_agent,\r\n \"scheme\": request.scheme,\r\n \"remote address\": request.remote_addr,\r\n \"headers\": request.headers,\r\n }\r\n if request.args:\r\n request_data[\"args\"] = request.args\r\n if request.form:\r\n request_data[\"data\"] = request.form\r\n else:\r\n request_data[\"data\"] = request.json\r\n if request.cookies:\r\n request_data[\"cookies\"] = request.cookies\r\n if request.files:\r\n request_data[\"image\"] = {\r\n \"filename\": request.files[\"Image\"].filename,\r\n \"content type\": request.files[\"Image\"].content_type,\r\n \"size\": len(request.files[\"Image\"].read()) // 1000,\r\n }\r\n app_logger.info(str(request_data))"}
101
+ {"file_name": "35b643c4-f349-475f-ad54-561e0f89c228.png", "code": "def log_get_request():\r\n request_data = {\r\n \"method\": request.method,\r\n \"url root\": request.url_root,\r\n \"user agent\": request.user_agent,\r\n \"scheme\": request.scheme,\r\n \"remote address\": request.remote_addr,\r\n \"headers\": request.headers,\r\n \"route\": request.endpoint,\r\n \"base url\": request.base_url,\r\n \"url\": request.url,\r\n }\r\n if request.args:\r\n request_data[\"args\"] = request.args\r\n if request.cookies:\r\n request_data[\"cookies\"] = request.cookies\r\n app_logger.info(str(request_data))\r\n\r\n\r\ndef get_response(response):\r\n response_data = {\r\n \"status\": response.status,\r\n \"status code\": response.status_code,\r\n \"response\": json.loads(response.data),\r\n }\r\n app_logger.info(str(response_data))"}
102
+ {"file_name": "24644e99-3f0c-4b4b-89f2-21e867c2bb93.png", "code": "def get_exception(exc):\r\n \"\"\"Log exceptions\"\"\"\r\n if exc:\r\n app_logger.warning(f\"{exc.__class__.__name__ }: {str(exc)}\")\r\n \r\n \r\ndef register_app_hooks(app: Flask):\r\n @app.before_first_request\r\n def application_startup():\r\n \"\"\"Log the beginning of the application.\"\"\"\r\n app_logger.info('Web app is up!')\r\n\r\n @app.before_request\r\n def log_request():\r\n \"\"\"Log the data held in the request\"\"\"\r\n if request.method in ['POST', 'PUT']:\r\n log_post_request()\r\n elif request.method in ['GET', 'DELETE']:\r\n log_get_request()\r\n\r\n @app.after_request\r\n def log_response(response):\r\n try:\r\n get_response(response)\r\n except Exception:\r\n pass\r\n finally:\r\n return response\r\n\r\n @app.teardown_request\r\n def log_exception(exc):\r\n get_exception(exc)"}