-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathposts.py
More file actions
161 lines (127 loc) · 5.85 KB
/
posts.py
File metadata and controls
161 lines (127 loc) · 5.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
from typing import Annotated, Any
from fastapi import APIRouter, Depends, Request
from fastcrud import PaginatedListResponse, compute_offset, paginated_response
from sqlalchemy.ext.asyncio import AsyncSession
from ...api.dependencies import get_current_superuser, get_current_user
from ...core.db.database import async_get_db
from ...core.exceptions.http_exceptions import ForbiddenException, NotFoundException
from ...core.utils.cache import cache
from ...crud.crud_posts import crud_posts
from ...crud.crud_users import crud_users
from ...schemas.post import PostCreate, PostCreateInternal, PostRead, PostUpdate
from ...schemas.user import UserRead
router = APIRouter(tags=["posts"])
@router.post("/{username}/post", response_model=PostRead, status_code=201)
async def write_post(
request: Request,
username: str,
post: PostCreate,
current_user: Annotated[dict, Depends(get_current_user)],
db: Annotated[AsyncSession, Depends(async_get_db)],
) -> dict[str, Any]:
db_user = await crud_users.get(db=db, username=username, is_deleted=False, schema_to_select=UserRead)
if db_user is None:
raise NotFoundException("User not found")
if current_user["id"] != db_user["id"]:
raise ForbiddenException()
post_internal_dict = post.model_dump()
post_internal_dict["created_by_user_id"] = db_user["id"]
post_internal = PostCreateInternal(**post_internal_dict)
created_post = await crud_posts.create(db=db, object=post_internal)
if created_post is None:
raise NotFoundException("Failed to create post")
post_read = await crud_posts.get(db=db, id=created_post["id"], schema_to_select=PostRead)
if post_read is None:
raise NotFoundException("Created post not found")
return post_read
@router.get("/{username}/posts", response_model=PaginatedListResponse[PostRead])
@cache(
key_prefix="{username}_posts:page_{page}:items_per_page:{items_per_page}",
resource_id_name="username",
expiration=60,
)
async def read_posts(
request: Request,
username: str,
db: Annotated[AsyncSession, Depends(async_get_db)],
page: int = 1,
items_per_page: int = 10,
) -> dict:
db_user = await crud_users.get(db=db, username=username, is_deleted=False, schema_to_select=UserRead)
if not db_user:
raise NotFoundException("User not found")
posts_data = await crud_posts.get_multi(
db=db,
offset=compute_offset(page, items_per_page),
limit=items_per_page,
created_by_user_id=db_user["id"],
is_deleted=False,
)
response: dict[str, Any] = paginated_response(crud_data=posts_data, page=page, items_per_page=items_per_page)
return response
@router.get("/{username}/post/{id}", response_model=PostRead)
@cache(key_prefix="{username}_post_cache", resource_id_name="id")
async def read_post(
request: Request, username: str, id: int, db: Annotated[AsyncSession, Depends(async_get_db)]
) -> dict[str, Any]:
db_user = await crud_users.get(db=db, username=username, is_deleted=False, schema_to_select=UserRead)
if db_user is None:
raise NotFoundException("User not found")
db_post = await crud_posts.get(
db=db, id=id, created_by_user_id=db_user["id"], is_deleted=False, schema_to_select=PostRead
)
if db_post is None:
raise NotFoundException("Post not found")
return db_post
@router.patch("/{username}/post/{id}")
@cache("{username}_post_cache", resource_id_name="id", pattern_to_invalidate_extra=["{username}_posts:*"])
async def patch_post(
request: Request,
username: str,
id: int,
values: PostUpdate,
current_user: Annotated[dict, Depends(get_current_user)],
db: Annotated[AsyncSession, Depends(async_get_db)],
) -> dict[str, str]:
db_user = await crud_users.get(db=db, username=username, is_deleted=False, schema_to_select=UserRead)
if db_user is None:
raise NotFoundException("User not found")
if current_user["id"] != db_user["id"]:
raise ForbiddenException()
db_post = await crud_posts.get(db=db, id=id, is_deleted=False, schema_to_select=PostRead)
if db_post is None:
raise NotFoundException("Post not found")
await crud_posts.update(db=db, object=values, id=id)
return {"message": "Post updated"}
@router.delete("/{username}/post/{id}")
@cache("{username}_post_cache", resource_id_name="id", to_invalidate_extra={"{username}_posts": "{username}"})
async def erase_post(
request: Request,
username: str,
id: int,
current_user: Annotated[dict, Depends(get_current_user)],
db: Annotated[AsyncSession, Depends(async_get_db)],
) -> dict[str, str]:
db_user = await crud_users.get(db=db, username=username, is_deleted=False, schema_to_select=UserRead)
if db_user is None:
raise NotFoundException("User not found")
if current_user["id"] != db_user["id"]:
raise ForbiddenException()
db_post = await crud_posts.get(db=db, id=id, is_deleted=False, schema_to_select=PostRead)
if db_post is None:
raise NotFoundException("Post not found")
await crud_posts.delete(db=db, id=id)
return {"message": "Post deleted"}
@router.delete("/{username}/db_post/{id}", dependencies=[Depends(get_current_superuser)])
@cache("{username}_post_cache", resource_id_name="id", to_invalidate_extra={"{username}_posts": "{username}"})
async def erase_db_post(
request: Request, username: str, id: int, db: Annotated[AsyncSession, Depends(async_get_db)]
) -> dict[str, str]:
db_user = await crud_users.get(db=db, username=username, is_deleted=False, schema_to_select=UserRead)
if db_user is None:
raise NotFoundException("User not found")
db_post = await crud_posts.get(db=db, id=id, is_deleted=False, schema_to_select=PostRead)
if db_post is None:
raise NotFoundException("Post not found")
await crud_posts.db_delete(db=db, id=id)
return {"message": "Post deleted from the database"}