Skip to content

Commit

Permalink
Исправить avatar на avatar_id для текущего кода (#146)
Browse files Browse the repository at this point in the history
В рамках работы над задачами добавления сваггера для профиля (#95), дружбы (#100) и желания (#104), мы предполагали, что файл будет иметь строковый тип и будет представлен ссылкой, поэтому в код сваггера мы добавили его в таком виде:
```python
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187"
```
И схемы для сваггера выглядели соответствующим образом:
```python
# src/profile/fields.py:
class Avatar(str):
    """Avatar value field."""

# src/profile/schemas.py:
class Profile(Schema):

    ...  # something here

    avatar: Avatar | None

    ...  # something here
```

Также исходя из этого предположения, во время работы над задачей реализации эндпойнта регистрации (#88) была добавлена колонка `avatar` в модель `Profile` с типом строка:
```python
avatar: Mapped[str | None] = mapped_column(String, unique=True)
```

Но после того, как мы начали работать над задачей добавления сваггера для эндпойнтов файла (#108), мы поняли, что вместо строкового типа нам надо использовать uuid в качестве идентификатора файла. Из этого следует, что нам необходимо внести следующие изменения в уже существующий код, описаный выше:

- Заменить `avatar` (string) на `avatar_id` (uuid) в существующих схемах и примерах сваггера
- Заменить `avatar` (string) на `avatar_id` (uuid) в существующей модели базы данных (`Profile`)

В рамках этой задачи необходимо внести изменения, описанные выше.

---

**Примечания**

Внесения подобных изменений можно было бы избежать, если бы схема для работы с файлами была продумана и добавлена в репозиторий заранее. Т.е. сваггер для эндпойнтов файлов, необходимо было добавить ещё до того, как будет добавлен хоть какой-то сваггер для эндпойнтов приложения, т.к. эндпойнты приложения используют файлы, и необходимо знать заранее как мы планируем работать с файлами.

Но поскольку это не было сделано вовремя, то сейчас необходимо внести правки в уже существующий функционал, а так же добавить сваггер для эндпойнтов файла (#108) и реализацию для них этих эндпойнтов, до того как будет добавлен какой-либо новый функционал приложения.
  • Loading branch information
birthdaysgift committed Nov 13, 2023
1 parent 0b641c6 commit 768108c
Show file tree
Hide file tree
Showing 12 changed files with 65 additions and 31 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""change avatar to avatar_id
Revision ID: 55f1606e7086
Revises: d7454b0101c0
Create Date: 2023-11-19 21:20:01.224200+00:00
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "55f1606e7086"
down_revision = "d7454b0101c0"
branch_labels = None
depends_on = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("profile", sa.Column("avatar_id", sa.UUID(), nullable=True))
op.create_unique_constraint("profile_avatar_id_key", "profile", ["avatar_id"])

op.drop_constraint("profile_avatar_key", "profile", type_="unique")
op.drop_column("profile", "avatar")
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("profile", sa.Column("avatar", sa.VARCHAR(), autoincrement=False, nullable=True))
op.create_unique_constraint("profile_avatar_key", "profile", ["avatar"])

op.drop_constraint("profile_avatar_id_key", "profile", type_="unique")
op.drop_column("profile", "avatar_id")
# ### end Alembic commands ###
2 changes: 1 addition & 1 deletion src/auth/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
},
"profile": {
"account_id": 42,
"avatar": None,
"avatar_id": None,
"description": "Who da heck is John Doe?",
"name": "John Doe",
},
Expand Down
4 changes: 2 additions & 2 deletions src/friendship/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"profile": {
"name": "John Doe",
"description": "Who da heck is John Doe?",
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
},
},
{
Expand All @@ -49,7 +49,7 @@
"profile": {
"name": "Alan Fresco",
"description": "Who da heck is Alan Fresco?",
"avatar": "/files/595f1db3-cdc6-4ef7-bbb4-33c4cedfe172",
"avatar_id": "595f1db3-cdc6-4ef7-bbb4-33c4cedfe172",
},
},
],
Expand Down
3 changes: 2 additions & 1 deletion src/friendship/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

from datetime import datetime
from uuid import UUID

from pydantic import PositiveInt

Expand Down Expand Up @@ -66,7 +67,7 @@ class FriendAccount(Schema):
class FriendProfile(Schema):
"""Profile info of someone's friend."""

avatar: profile_fields.Avatar
avatar_id: UUID | None
description: profile_fields.Description
name: profile_fields.Name

Expand Down
4 changes: 0 additions & 4 deletions src/profile/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
from src.shared.fields import StrField


class Avatar(str):
"""Avatar value field."""


class Description(StrField):
"""Description value field."""

Expand Down
4 changes: 3 additions & 1 deletion src/profile/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

from datetime import datetime
from typing import TYPE_CHECKING
from uuid import UUID

from sqlalchemy import DateTime, ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column

from src.shared.database import Base
Expand All @@ -25,7 +27,7 @@ class Profile(Base): # pylint: disable=too-few-public-methods

account_id: Mapped[int] = mapped_column(ForeignKey("account.id"), autoincrement=False, primary_key=True)

avatar: Mapped[str | None] = mapped_column(String, unique=True)
avatar_id: Mapped[UUID | None] = mapped_column(PG_UUID(as_uuid=True), unique=True)
description: Mapped[String | None] = mapped_column(String)
name: Mapped[str] = mapped_column(String, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
Expand Down
6 changes: 3 additions & 3 deletions src/profile/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"account_id": 42,
"name": "John Doe",
"description": "Who da heck is John Doe?",
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
},
},
},
Expand Down Expand Up @@ -60,7 +60,7 @@ def get_profile(
"account_id": 42,
"name": "John Doe",
"description": "Who da heck is John Doe?",
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
},
},
},
Expand All @@ -81,7 +81,7 @@ def update_profile(
example={
"name": "John Doe",
"description": "Who da heck is John Doe?",
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
},
),
],
Expand Down
8 changes: 5 additions & 3 deletions src/profile/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

from __future__ import annotations

from uuid import UUID

from pydantic import PositiveInt

from src.profile.fields import Avatar, Description, Name
from src.profile.fields import Description, Name
from src.shared.schemas import Schema


Expand All @@ -13,7 +15,7 @@ class Profile(Schema):

account_id: PositiveInt

avatar: Avatar | None
avatar_id: UUID | None
description: Description | None
name: Name

Expand All @@ -26,6 +28,6 @@ class Config:
class ProfileUpdate(Schema):
"""Data for Profile update."""

avatar: Avatar | None
avatar_id: UUID | None
description: Description | None
name: Name
4 changes: 0 additions & 4 deletions src/wish/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
from src.shared.fields import StrField


class Avatar(str):
"""Avatar value field."""


class Description(StrField):
"""Description value field."""

Expand Down
12 changes: 6 additions & 6 deletions src/wish/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"example": {
"id": 17,
"account_id": 42,
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
"title": "Horse",
"description": "I'm gonna take my horse to the old town road.",
"created_at": "2023-06-17T11:47:02.823Z",
Expand All @@ -51,7 +51,7 @@ async def create_wish(
example={
"title": "Horse",
"description": "I'm gonna take my horse to the old town road.",
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
},
),
],
Expand All @@ -71,7 +71,7 @@ async def create_wish(
"example": {
"id": 17,
"account_id": 42,
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
"title": "Horse",
"description": "I'm gonna take my horse to the old town road.",
"created_at": "2023-06-17T11:47:02.823Z",
Expand All @@ -94,7 +94,7 @@ async def update_wish(
schemas.WishUpdate,
Body(
example={
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
"title": "Horse",
"description": "I'm gonna take my horse to the old town road.",
},
Expand Down Expand Up @@ -141,15 +141,15 @@ async def delete_wish(
{
"id": 17,
"account_id": 42,
"avatar": "/files/0b928aaa-521f-47ec-8be5-396650e2a187",
"avatar_id": "0b928aaa-521f-47ec-8be5-396650e2a187",
"title": "Horse",
"description": "I'm gonna take my horse to the old town road.",
"created_at": "2023-06-17T11:47:02.823Z",
},
{
"id": 21,
"account_id": 42,
"avatar": "/files/92f97bc4-c3d3-4980-86c8-0131c1bedffc",
"avatar_id": "92f97bc4-c3d3-4980-86c8-0131c1bedffc",
"title": "Sleep",
"description": "I need some sleep. Time to put the old horse down.",
"created_at": "2023-10-11T18:31:42.715Z",
Expand Down
9 changes: 5 additions & 4 deletions src/wish/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
from __future__ import annotations

from datetime import datetime
from uuid import UUID

from pydantic import PositiveInt

from src.shared.schemas import Schema
from src.wish.fields import Avatar, Description, Title
from src.wish.fields import Description, Title


class Wish(Schema):
Expand All @@ -16,7 +17,7 @@ class Wish(Schema):
id: PositiveInt # noqa: A003

account_id: PositiveInt
avatar: Avatar | None
avatar_id: UUID | None
created_at: datetime
description: Description
title: Title
Expand All @@ -31,15 +32,15 @@ class Wishes(Schema):
class NewWish(Schema):
"""Wish which is going to be created."""

avatar: Avatar | None
avatar_id: UUID | None
description: Description
title: Title


class WishUpdate(Schema):
"""Update info for wish."""

avatar: Avatar | None
avatar_id: UUID | None
description: Description
title: Title

Expand Down
4 changes: 2 additions & 2 deletions tests/test_auth/test_create_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async def test_create_account_returns_201_with_correct_body(f):
},
"profile": {
"account_id": dirty_equals.IsPositiveInt,
"avatar": None,
"avatar_id": None,
"description": "I'm the best guy for your mocks.",
"name": "John Doe",
},
Expand Down Expand Up @@ -90,7 +90,7 @@ async def test_create_account_creates_objects_in_db_correctly(f):
assert profiles == [
Profile(
account_id=dirty_equals.IsPositiveInt,
avatar=None,
avatar_id=None,
description="I'm the best guy for your mocks.",
name="John Doe",
updated_at=datetime(2023, 10, 30, 20, 0, tzinfo=timezone.utc),
Expand Down

0 comments on commit 768108c

Please sign in to comment.