Skip to content

Commit

Permalink
Create requests to the service to receive data (#6)
Browse files Browse the repository at this point in the history
* Update settings

* Update validate for password

* Move packets with the schemas

* Create base of exceptions for requests

* Create requests to the service to receive data

* Update protocols

* Update schemas
  • Loading branch information
WolfMTK authored Jan 24, 2024
1 parent 4d05193 commit 9fc921a
Show file tree
Hide file tree
Showing 11 changed files with 202 additions and 4 deletions.
17 changes: 16 additions & 1 deletion backend/src/application/protocols/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,30 @@

from src.infrastructure.db import Base


ModelType = TypeVar("ModelType", bound=Base)


class AbstractRepository(ABC):
@abstractmethod
async def add_one(self):
...

@abstractmethod
async def update_one(self):
...

@abstractmethod
async def find_one(self):
...

@abstractmethod
async def find_all(self):
...

@abstractmethod
async def delete_one(self):
...


class SQLAlchemyRepository(AbstractRepository):
model: ModelType | None = None
Expand Down
2 changes: 1 addition & 1 deletion backend/src/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
class Settings:
"""Настройки проекта."""

db_url: str = os.getenv("DB_URL") or "sqlite+aiosqlite:///sqlite.db"
db_url: str = os.getenv("DB_URL", "sqlite+aiosqlite:///sqlite.db")
app_title = "API для проекта 'Созидатели'."
admin_panel_user = os.getenv("ADMIN_PANEL_USER")
admin_panel_password = os.getenv("ADMIN_PANEL_PASSWORD")
5 changes: 3 additions & 2 deletions backend/src/domain/schemas/users.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import re

from pydantic import BaseModel, ConfigDict, EmailStr, Field, validator
from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator

from src.domain.models.assistance import AssistanceSegment

Expand All @@ -26,7 +26,8 @@ class UserCreate(BaseModel):
meeting_id: int
assistance_segment: AssistanceSegment | None = "not_decide"

@validator("phone")
@field_validator("phone")
@classmethod
def validate_phone(cls, value):
if not re.match(NUMBER_RE, value):
raise ValueError(
Expand Down
1 change: 1 addition & 0 deletions bot/src/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ class Settings:
bot_token: str = os.getenv('BOT_TOKEN')
throttle_time_spin: int = os.getenv('THROTTLE_TIME_SPIN')
throttle_time_other: int = os.getenv('THROTTLE_TIME_OTHER')
url: str = os.getenv('URL', 'http://localhost:8000')
Empty file added bot/src/schemas/__init__.py
Empty file.
33 changes: 33 additions & 0 deletions bot/src/schemas/meetings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from datetime import datetime

from pydantic import BaseModel, ConfigDict

from .users import GetUser


class MeetingCreate(BaseModel):
date: datetime
description: str


class GetMeeting(BaseModel):
model_config = ConfigDict(from_attributes=True)

id: int
date: datetime
is_open: bool
description: str


class MeetingUpdate(BaseModel):
date: datetime | None = None
is_open: bool | None = None
description: str | None = None


class MeetingParticipants(BaseModel):
id: int
date: datetime
is_open: bool
description: str
users: list[GetUser]
25 changes: 25 additions & 0 deletions bot/src/schemas/users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from pydantic import BaseModel, ConfigDict, EmailStr, Field


class GetUser(BaseModel):
model_config = ConfigDict(from_attributes=True)

id: int
name: str
phone: str
email: EmailStr
meeting_id: int


class UserCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=255)
phone: str
email: EmailStr
meeting_id: int


class UserUpdate(BaseModel):
name: str | None = None
phone: str | None = None
email: EmailStr | None = None
meeting_id: int | None = None
Empty file added bot/src/services/__init__.py
Empty file.
2 changes: 2 additions & 0 deletions bot/src/services/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class HTTPRequestError(Exception):
"""Ошибка запроса к серверу."""
69 changes: 69 additions & 0 deletions bot/src/services/meetings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from collections import Generator
from http import HTTPStatus

import aiohttp
from aiohttp import ClientResponse

from src.core import settings
from src.schemas import meetings
from src.services.exceptions import HTTPRequestError


class MeetingService:
def __init__(self):
self._path = '/meetings'

async def get_meetings(self) -> Generator[meetings.GetMeeting]:
async with aiohttp.ClientSession(settings.url) as session:
async with session.get(self._path) as response:
return await self._get_meetings(response)

async def create_meeting(self,
meeting: meetings.MeetingCreate) -> meetings.GetMeeting:
async with aiohttp.ClientSession(settings.url) as session:
async with session.post(
self._path, data=meeting.model_dump()
) as response:
if response.status == HTTPStatus.OK:
return meetings.GetMeeting(**(await response.json()))
raise HTTPRequestError('Ошибка запроса! Повторите снова!')

async def update_meeting(
self,
id: int,
meeting: meetings.MeetingUpdate
) -> meetings.GetMeeting:
async with aiohttp.ClientSession(settings.url) as session:
async with session.patch(
f'{self._path}/{id}', data=meeting.model_dump()
) as response:
return await self._get_meeting(response)

async def delete_meeting(self, id: int):
async with aiohttp.ClientSession(settings.url) as session:
async with session.delete(f'{self._path}/{id}') as response:
if not (response.status == HTTPStatus.OK):
raise HTTPRequestError('Ошибка запроса! Повторите снова!')

async def get_participants_list(self, id: int):
async with aiohttp.ClientSession(settings.url) as session:
async with session.get(
f'{self._path}/{id}/participants') as response:
if response.status == HTTPStatus.OK:
return meetings.MeetingParticipants(
**(await response.json()))
raise HTTPRequestError('Ошибка запроса! Повторите снова!')

async def _get_meeting(self,
response: ClientResponse) -> meetings.GetMeeting:
if response.status == HTTPStatus.OK:
return meetings.GetMeeting(**(await response.json()))
raise HTTPRequestError('Ошибка запроса! Повторите снова!')

async def _get_meetings(
self, response: ClientResponse
) -> Generator[meetings.GetMeeting]:
if response.status == HTTPStatus.OK:
return (meetings.GetMeeting(**json) for json in
await response.json())
raise HTTPRequestError('Ошибка запроса! Повторите снова!')
52 changes: 52 additions & 0 deletions bot/src/services/users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from collections import Generator
from http import HTTPStatus

import aiohttp
from aiohttp import ClientResponse

from src.core import settings
from src.schemas import users
from src.services.exceptions import HTTPRequestError


class UserService:
def __init__(self):
self._path = '/users'

async def get_users(self) -> Generator[users.GetUser]:
async with aiohttp.ClientSession(settings.url) as session:
async with session.get(self._path) as response:
return await self._get_users(response)

async def create_user(self, user: users.UserCreate) -> users.GetUser:
async with aiohttp.ClientSession(settings.url) as session:
async with session.post(self._path,
data=user.model_dump()) as response:
return await self._get_user(response)

async def update_user(self, id: int,
user: users.UserUpdate) -> users.GetUser:
async with aiohttp.ClientSession(settings.url) as session:
async with session.post(f'self._path/{id}',
data=user.model_dump()) as response:
return await self._get_user(response)

async def delete_user(self, id: int):
async with aiohttp.ClientSession(settings.url) as session:
async with session.delete(f'{self._path}/{id}') as response:
if not (response.status == HTTPStatus.OK):
raise HTTPRequestError('Ошибка запроса! Повторите снова!')

async def _get_user(self,
response: ClientResponse) -> users.GetUser:
if response.status == HTTPStatus.OK:
return users.GetUser(**(await response.json()))
raise HTTPRequestError('Ошибка запроса! Повторите снова!')

async def _get_users(
self, response: ClientResponse
) -> Generator[users.GetUser]:
if response.status == HTTPStatus.OK:
return (users.GetUser(**json) for json in
await response.json())
raise HTTPRequestError('Ошибка запроса! Повторите снова!')

0 comments on commit 9fc921a

Please sign in to comment.