From 0daa6af89982f53476919accc9936f3f1480a686 Mon Sep 17 00:00:00 2001 From: Aykhan Date: Wed, 13 Sep 2023 23:26:06 +0400 Subject: [PATCH] Added delete post page --- src/app/core/config.py | 4 ++ src/app/crud/crud_post.py | 9 ++++ src/app/crud/crud_user.py | 17 ++++++-- src/app/db/base_class.py | 5 ++- src/app/models/user.py | 7 ++- src/app/schemas/post.py | 47 ++++++++++++++++----- src/app/templates/admin/delete-post.html | 31 ++++++++++++++ src/app/templates/admin/update-post.html | 2 +- src/app/templates/blog.html | 15 +++++-- src/app/templates/index.html | 2 +- src/app/templates/post.html | 26 +++--------- src/app/utils/custom_functions.py | 9 ++++ src/app/views/depends.py | 1 - src/app/views/routers/main.py | 25 +++++++++++ src/app/views/routers/user.py | 54 +++++++++++++++++++++--- 15 files changed, 205 insertions(+), 49 deletions(-) create mode 100644 src/app/templates/admin/delete-post.html create mode 100644 src/app/utils/custom_functions.py diff --git a/src/app/core/config.py b/src/app/core/config.py index 35c6750..fea112a 100644 --- a/src/app/core/config.py +++ b/src/app/core/config.py @@ -30,6 +30,10 @@ class Settings(BaseSettings): POSTGRES_PORT: int = 5432 POSTGRES_DB: str + @property + def LOGIN_URL(self) -> str: + return self.SECRET_KEY[-10:] + def get_postgres_dsn(self, _async: bool=False) -> PostgresDsn: scheme = 'postgresql+asyncpg' if _async else 'postgresql' diff --git a/src/app/crud/crud_post.py b/src/app/crud/crud_post.py index 0c75c59..1972130 100644 --- a/src/app/crud/crud_post.py +++ b/src/app/crud/crud_post.py @@ -66,4 +66,13 @@ class CRUDPost(CRUDBase[Post, PostCreate, PostUpdate]): def create(self): raise DeprecationWarning("Use create_with_owner instead") + async def remove_by_slug(self, db: Session, *, slug: str) -> Post: + q = select(self.model).where(self.model.slug == slug) + obj = await db.execute(q) + obj = obj.scalar_one() + await db.delete(obj) + await db.commit() + + return obj + post = CRUDPost(Post) \ No newline at end of file diff --git a/src/app/crud/crud_user.py b/src/app/crud/crud_user.py index c588f65..fce901f 100644 --- a/src/app/crud/crud_user.py +++ b/src/app/crud/crud_user.py @@ -1,12 +1,23 @@ -from typing import Any, Dict, Optional, Union +from typing import ( + Any, + Dict, + Optional, + Union +) from sqlalchemy.orm import Session from sqlalchemy.future import select -from app.core.security import get_password_hash, verify_password +from app.core.security import ( + get_password_hash, + verify_password +) from app.crud.base import CRUDBase from app.models.user import User -from app.schemas.user import UserCreate, UserUpdate +from app.schemas.user import ( + UserCreate, + UserUpdate +) class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]): diff --git a/src/app/db/base_class.py b/src/app/db/base_class.py index df4c135..9a98a85 100644 --- a/src/app/db/base_class.py +++ b/src/app/db/base_class.py @@ -1,6 +1,9 @@ from typing import Any -from sqlalchemy.ext.declarative import as_declarative, declared_attr +from sqlalchemy.ext.declarative import ( + as_declarative, + declared_attr +) from sqlalchemy import ( DateTime, Column diff --git a/src/app/models/user.py b/src/app/models/user.py index 78f5d96..6d85ea1 100644 --- a/src/app/models/user.py +++ b/src/app/models/user.py @@ -1,4 +1,9 @@ -from sqlalchemy import Boolean, Column, Integer, String +from sqlalchemy import ( + Boolean, + Column, + Integer, + String +) from sqlalchemy.orm import relationship from app.db.base_class import Base diff --git a/src/app/schemas/post.py b/src/app/schemas/post.py index ae93056..03d6fee 100644 --- a/src/app/schemas/post.py +++ b/src/app/schemas/post.py @@ -4,13 +4,16 @@ from pydantic import ( BaseModel, Field, PastDatetime, - computed_field, - TypeAdapter + TypeAdapter, + field_validator ) +from app.utils.custom_functions import html2text + from app.core.config import settings + class PostBase(BaseModel): title: Optional[str] = Field(max_length=100) text: Optional[str] = None @@ -26,23 +29,48 @@ class PostCreate(PostBase): class PostUpdate(PostBase): ... -class PostInTemplate(PostBase): +class PostInTemplate(BaseModel): title: str text: str created_at: PastDatetime + slug: str class Config: from_attributes = True + @field_validator('text', mode='after') + @classmethod + def html_to_text(cls, v: str) -> str: + return html2text(v)[:60] + ListPostInTemplate = TypeAdapter(list[PostInTemplate]) +class PostDetail(BaseModel): + title: str + text: str + created_at: PastDatetime + image_path: str + + class Config: + from_attributes = True + + @field_validator('image_path', mode='after') + @classmethod + def absolute_image_path(cls, v: str) -> str | None: + return str( + settings.MEDIA_FOLDER / + settings.FILE_FOLDERS['post_images'] / + v + ) + + class PostInDBBase(PostBase): slug: str title: str text: str - image_path: Optional[str] = None + image_path: str owner_id: int class Config: @@ -50,14 +78,11 @@ class PostInDBBase(PostBase): class Post(PostInDBBase): - @computed_field - @property - def image_url(self) -> str | None: - if self.image_path is None: - return None - + @field_validator('image_path', mode='after') + @classmethod + def absolute_image_path(cls, v: str) -> str | None: return str( settings.MEDIA_FOLDER / settings.FILE_FOLDERS['post_images'] / - self.image_path + v ) \ No newline at end of file diff --git a/src/app/templates/admin/delete-post.html b/src/app/templates/admin/delete-post.html new file mode 100644 index 0000000..8552fdb --- /dev/null +++ b/src/app/templates/admin/delete-post.html @@ -0,0 +1,31 @@ + + + + + + + Update Post + + + + + + +
+
+
+

Are you sure you want to delete {{post.title}}?

+
+
+ +
+ No +
+
+
+
+ + + + + \ No newline at end of file diff --git a/src/app/templates/admin/update-post.html b/src/app/templates/admin/update-post.html index 84b21dd..10097ff 100644 --- a/src/app/templates/admin/update-post.html +++ b/src/app/templates/admin/update-post.html @@ -45,7 +45,7 @@
-

Current: {{post.image_url}}

+

Current: {{post.image_path}}

diff --git a/src/app/templates/blog.html b/src/app/templates/blog.html index 5c45987..efee8d3 100644 --- a/src/app/templates/blog.html +++ b/src/app/templates/blog.html @@ -3,7 +3,7 @@ {% block title %}Blog{% endblock title %} {% block content %} -
+
@@ -21,11 +21,15 @@
{% for post in posts %}
- +

{{post.title}}

{{post.text}}

- + + {% if user %} + Update + Delete + {% endif %}

{% endfor %} @@ -39,6 +43,11 @@
{% endif %} + {% if user %} + + Add + + {% endif %}
diff --git a/src/app/templates/index.html b/src/app/templates/index.html index 0fbcf6f..98bb14b 100644 --- a/src/app/templates/index.html +++ b/src/app/templates/index.html @@ -3,7 +3,7 @@ {% block title %}Just a Page{% endblock title %} {% block content %} -
+
diff --git a/src/app/templates/post.html b/src/app/templates/post.html index 152adbe..e354430 100644 --- a/src/app/templates/post.html +++ b/src/app/templates/post.html @@ -2,14 +2,15 @@ {% block title %}Blog Post{% endblock title %} + {% block content %} -
+
-

Title

Date +

{{post.title}}

{{post.created_at.strftime('%Y-%m-%d %H:%M')}}
@@ -19,25 +20,8 @@
-

Never in all their history have men been able truly to conceive of the world as one: a single sphere, a globe, having the qualities of a globe, a round earth in which all the directions eventually meet, in which there is no center because every point, or none, is center — an equal earth which all men occupy as equals. The airman's earth, if free men make it, will be truly round: a globe in practice, not in theory.

-

Science cuts two ways, of course; its products can be used for both good and evil. But there's no turning back from science. The early warnings about technological dangers also come from science.

-

What was most significant about the lunar voyage was not that man set foot on the Moon but that they set eye on the earth.

-

A Chinese tale tells of some men sent to harm a young girl who, upon seeing her beauty, become her protectors rather than her violators. That's how I felt seeing the Earth for the first time. I could not help but love and cherish her.

-

For those who have seen the Earth from space, and for the hundreds and perhaps thousands more who will, the experience most certainly changes your perspective. The things that we share in our world are far more valuable than those which divide us.

-

Heading

-

There can be no thought of finishing for ‘aiming for the stars.’ Both figuratively and literally, it is a task to occupy the generations. And no matter how much progress one makes, there is always the thrill of just beginning.

-

There can be no thought of finishing for ‘aiming for the stars.’ Both figuratively and literally, it is a task to occupy the generations. And no matter how much progress one makes, there is always the thrill of just beginning.

-
-
-

The dreams of yesterday are the hopes of today and the reality of tomorrow. Science has not yet mastered prophecy. We predict too much for the next year and yet far too little for the next ten.

-
-
-

Spaceflights cannot be stopped. This is not the work of any one man or even a group of men. It is a historical process which mankind is carrying out in accordance with the natural laws of human development.

-

Reaching for the Stars

-

As we got further and further away, it [the Earth] diminished in size. Finally it shrank to the size of a marble, the most beautiful you can imagine. That beautiful, warm, living object looked so fragile, so delicate, that if you touched it with a finger it would crumble and fall apart. Seeing this has to change a man.

To go places and do things that have never been done before – that’s what living is all about. -

Space, the final frontier. These are the voyages of the Starship Enterprise. Its five-year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before.

-

As I stand out here in the wonders of the unknown at Hadley, I sort of realize there’s a fundamental truth to our nature, Man must explore, and this is exploration at its greatest.

-

Placeholder text by Space Ipsum Photographs by NASA on The Commons.

+ + {{post.text|safe}}
diff --git a/src/app/utils/custom_functions.py b/src/app/utils/custom_functions.py new file mode 100644 index 0000000..90832a0 --- /dev/null +++ b/src/app/utils/custom_functions.py @@ -0,0 +1,9 @@ +import re + + +def html2text(html: str) -> str: + return re.sub( + re.compile('<.*?>'), + '', + html + ) \ No newline at end of file diff --git a/src/app/views/depends.py b/src/app/views/depends.py index 48374d5..960ac30 100644 --- a/src/app/views/depends.py +++ b/src/app/views/depends.py @@ -15,7 +15,6 @@ from sqlalchemy.ext.asyncio import AsyncSession from fastapi import ( Cookie, Depends, - File, HTTPException, UploadFile, status diff --git a/src/app/views/routers/main.py b/src/app/views/routers/main.py index 0cc818d..789b6be 100644 --- a/src/app/views/routers/main.py +++ b/src/app/views/routers/main.py @@ -19,6 +19,7 @@ from app import crud from app.core.config import settings from app.schemas import ListPostInTemplate from app.schemas.main import SendEmail +from app.schemas.post import PostDetail from app.utils.email_utils import send_email_notification from app.models.user import User as UserModel from app.views.depends import ( @@ -94,4 +95,28 @@ async def blog( 'skip': skip, 'user': user } + ) + + +@router.get('/blog/{slug}', response_class=HTMLResponse) +async def blog_post( + request: Request, + slug: str, + db: AsyncSession = Depends(get_async_db) +): + + post = await crud.post.get_by_slug(db, slug=slug) + + if post is None: + return RedirectResponse( + str(request.url_for('blog')), + status_code=303 + ) + + return templates.TemplateResponse( + 'post.html', + { + 'request': request, + 'post': PostDetail.model_validate(post) + } ) \ No newline at end of file diff --git a/src/app/views/routers/user.py b/src/app/views/routers/user.py index 9bebd45..78a0247 100644 --- a/src/app/views/routers/user.py +++ b/src/app/views/routers/user.py @@ -1,5 +1,8 @@ from datetime import timedelta -from typing import Annotated, Optional +from typing import ( + Annotated, + Optional +) from sqlalchemy.ext.asyncio import AsyncSession @@ -46,7 +49,7 @@ templates = Jinja2Templates(directory=settings.APP_PATH / 'templates') @router.get( - f"/{settings.SECRET_KEY[-10:]}", + f"/{settings.LOGIN_URL}", response_class=HTMLResponse, include_in_schema=False ) @@ -58,13 +61,13 @@ async def login( 'admin/login.html', { 'request': request, - 'login_url': f'/{settings.SECRET_KEY[-10:]}' + 'login_url': f'/{settings.LOGIN_URL}' } ) @router.post( - f"/{settings.SECRET_KEY[-10:]}", + f"/{settings.LOGIN_URL}", response_model=JWTToken, include_in_schema=False ) @@ -144,7 +147,7 @@ async def get_update_post( if user is None: return RedirectResponse( - f'/{settings.SECRET_KEY[-10:]}', + f'/{settings.LOGIN_URL}', status_code=303 ) @@ -173,7 +176,7 @@ async def update_post( if user is None: return RedirectResponse( - f'/{settings.SECRET_KEY[-10:]}', + f'/{settings.LOGIN_URL}', status_code=303 ) @@ -200,6 +203,45 @@ async def update_post( } ) + +@router.get('/delete-post/{slug}') +async def get_delete_post( + request: Request, + user: UserModel = Depends(get_current_active_superuser_or_die), + post: str = Depends(get_post_by_slug_or_die) +): + + if user.id != post.owner_id: + raise HTTPException(status_code=404, detail="Post not found") + + return templates.TemplateResponse( + 'admin/delete-post.html', + { + 'request': request, + 'post': PostSchema.model_validate(post) + } + ) + + +@router.post('/delete-post/{slug}') +async def delete_post( + request: Request, + user: UserModel = Depends(get_current_active_superuser_or_die), + post: str = Depends(get_post_by_slug_or_die), + db: AsyncSession = Depends(get_async_db) +): + + if user.id != post.owner_id: + raise HTTPException(status_code=404, detail="Post not found") + + await crud.post.remove_by_slug(db, slug=post.slug) + + return RedirectResponse( + str(request.url_for('blog')), + status_code=303 + ) + + @router.get("/admin") def admin( request: Request