Skip to content

Commit

Permalink
Merge pull request #66
Browse files Browse the repository at this point in the history
Add extra preferences field in Manas ID model
  • Loading branch information
usbtypec1 authored Jan 4, 2024
2 parents 0778ab2 + 9eef4af commit 48bf9da
Show file tree
Hide file tree
Showing 18 changed files with 477 additions and 470 deletions.
656 changes: 326 additions & 330 deletions poetry.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "duck-duck-bot"
version = "1.18.3"
version = "1.18.4"
description = ""
authors = ["Eldos <[email protected]>"]
readme = "README.md"
Expand All @@ -14,6 +14,7 @@ sentry-sdk = "^1.38.0"
structlog = "^23.2.0"
humanize = "^4.9.0"
cloudinary = "^1.36.0"
httpx = "^0.26.0"


[tool.poetry.group.dev.dependencies]
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import aiohttp
import httpx
import structlog
from aiogram import Router
from aiogram.filters import ExceptionTypeFilter
Expand All @@ -18,7 +18,7 @@
router = Router(name=__name__)


@router.error(ExceptionTypeFilter(aiohttp.ClientConnectorError))
@router.error(ExceptionTypeFilter(httpx.ConnectError))
async def on_client_connector_error(event: ErrorEvent) -> None:
update = event.update
text = f'❌ Ошибка клиентского соединения:\n{str(event.exception)}'
Expand Down
7 changes: 3 additions & 4 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
import pathlib
from functools import partial

import aiohttp
import cloudinary
import httpx
import humanize
import sentry_sdk
import structlog
from aiogram import Bot, Dispatcher
from aiogram.enums import ParseMode
from aiogram.fsm.storage.redis import RedisStorage
from aiohttp import ClientTimeout
from redis.asyncio import Redis
from structlog.stdlib import BoundLogger

Expand Down Expand Up @@ -100,9 +99,9 @@ async def main() -> None:
dispatcher['anonymous_message_sender'] = AnonymousMessageSender(bot)
dispatcher['bot_user'] = bot_user
dispatcher['closing_http_client_factory'] = partial(
aiohttp.ClientSession,
httpx.AsyncClient,
base_url=config.server_api_base_url,
timeout=ClientTimeout(60),
timeout=60,
)
dispatcher['chat_id_for_retranslation'] = config.main_chat_id
dispatcher['timezone'] = config.timezone
Expand Down
4 changes: 2 additions & 2 deletions src/middlewares/api_repositories_initializer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import aiohttp
import httpx
from aiogram import BaseMiddleware
from aiogram.types import Update

Expand All @@ -19,7 +19,7 @@ async def __call__(
event: Update,
data: ContextData,
) -> HandlerReturn:
http_client: aiohttp.ClientSession = data['http_client']
http_client: httpx.AsyncClient = data['http_client']
for name, api_repository_type in self.__name_to_api_repository.items():
data[name] = api_repository_type(http_client)
return await handler(event, data)
6 changes: 6 additions & 0 deletions src/models/manas_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
__all__ = ('ManasId',)


class ExtraPreference(BaseModel):
name: str
value: str


class ManasId(BaseModel):
user_id: int
department: Department
Expand All @@ -25,3 +30,4 @@ class ManasId(BaseModel):
nationality: str | None
region: str | None
country: str | None
extra_preferences: list[ExtraPreference]
58 changes: 29 additions & 29 deletions src/repositories/balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@ async def create_transfer(
'amount': amount,
'description': description,
}
async with self._http_client.post(url, json=request_data) as response:
if response.status == 400:
response_data = await response.json()
if response_data[0] == 'Insufficient funds for transfer':
raise InsufficientFundsForTransferError
if response.status != 201:
raise ServerAPIError
response_data = await response.json()
response = await self._http_client.post(url, json=request_data)
if response.status_code == 400:
response_data = response.json()
if response_data[0] == 'Insufficient funds for transfer':
raise InsufficientFundsForTransferError
if response.status_code != 201:
raise ServerAPIError
response_data = response.json()
return Transfer.model_validate(response_data)

async def create_withdrawal(
Expand All @@ -50,14 +50,14 @@ async def create_withdrawal(
'amount': amount,
'description': description,
}
async with self._http_client.post(url, json=request_data) as response:
if response.status == 400:
response_data = await response.json()
if response_data[0] == 'Insufficient funds for withdrawal':
raise InsufficientFundsForWithdrawalError(amount=amount)
if response.status != 201:
raise ServerAPIError
response_data = await response.json()
response = await self._http_client.post(url, json=request_data)
if response.status_code == 400:
response_data = response.json()
if response_data[0] == 'Insufficient funds for withdrawal':
raise InsufficientFundsForWithdrawalError(amount=amount)
if response.status_code != 201:
raise ServerAPIError
response_data = response.json()
return SystemTransaction.model_validate(response_data)

async def create_deposit(
Expand All @@ -73,20 +73,20 @@ async def create_deposit(
'amount': amount,
'description': description,
}
async with self._http_client.post(url, json=request_data) as response:
if response.status != 201:
raise ServerAPIError
response_data = await response.json()
response = await self._http_client.post(url, json=request_data)
if response.status_code != 201:
raise ServerAPIError
response_data = response.json()
return SystemTransaction.model_validate(response_data)

async def get_user_balance(self, user_id: int) -> UserBalance:
url = f'/economics/balance/users/{user_id}/'
async with self._http_client.get(url) as response:
if response.status == 404:
raise UserDoesNotExistError(user_id=user_id)
if response.status != 200:
raise ServerAPIError
response_data = await response.json()
response = await self._http_client.get(url)
if response.status_code == 404:
raise UserDoesNotExistError(user_id=user_id)
if response.status_code != 200:
raise ServerAPIError
response_data = response.json()
return UserBalance.model_validate(response_data)

async def create_richest_users_statistics_task(
Expand All @@ -100,6 +100,6 @@ async def create_richest_users_statistics_task(
'chat_id': chat_id,
'user_id': user_id,
}
async with self._http_client.post(url, json=request_data) as response:
if response.status != 202:
raise ServerAPIError
response = await self._http_client.post(url, json=request_data)
if response.status_code != 202:
raise ServerAPIError
6 changes: 3 additions & 3 deletions src/repositories/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from collections.abc import Callable
from typing import TypeAlias

import aiohttp
import httpx
from redis.asyncio import Redis

__all__ = (
Expand All @@ -10,12 +10,12 @@
'RedisRepository',
)

HTTPClientFactory: TypeAlias = Callable[..., aiohttp.ClientSession]
HTTPClientFactory: TypeAlias = Callable[..., httpx.AsyncClient]


class APIRepository:

def __init__(self, http_client: aiohttp.ClientSession):
def __init__(self, http_client: httpx.AsyncClient):
self._http_client = http_client


Expand Down
64 changes: 32 additions & 32 deletions src/repositories/contacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,40 +30,40 @@ async def create(
'public_name': public_name,
}
url = '/contacts/'
async with self._http_client.post(url, json=request_data) as response:
if response.status == 400:
response_data = await response.json()
error_detail = response_data.get('detail')
if error_detail == 'Insufficient funds for contact creation':
amount = response_data['amount']
raise InsufficientFundsForWithdrawalError(amount=amount)
if response.status == 404:
raise UserDoesNotExistError(user_id=of_user_id)
if response.status == 409:
raise ContactAlreadyExistsError
if response.status != 201:
raise ServerAPIError
response_data = await response.json()
response = await self._http_client.post(url, json=request_data)
if response.status_code == 400:
response_data = response.json()
error_detail = response_data.get('detail')
if error_detail == 'Insufficient funds for contact creation':
amount = response_data['amount']
raise InsufficientFundsForWithdrawalError(amount=amount)
if response.status_code == 404:
raise UserDoesNotExistError(user_id=of_user_id)
if response.status_code == 409:
raise ContactAlreadyExistsError
if response.status_code != 201:
raise ServerAPIError
response_data = response.json()
return models.Contact.model_validate(response_data)

async def get_by_user_id(
self,
user_id: int,
) -> list[models.Contact]:
url = f'/users/{user_id}/contacts/'
async with self._http_client.get(url) as response:
if response.status != 200:
raise ServerAPIError
response_data = await response.json()
response = await self._http_client.get(url)
if response.status_code != 200:
raise ServerAPIError
response_data = response.json()
type_adapter = TypeAdapter(list[models.Contact])
return type_adapter.validate_python(response_data)

async def get_by_id(self, contact_id: int) -> models.Contact:
url = f'/contacts/{contact_id}/'
async with self._http_client.get(url) as response:
if response.status == 404:
raise ContactDoesNotExistError(contact_id=contact_id)
response_data = await response.json()
response = await self._http_client.get(url)
if response.status_code == 404:
raise ContactDoesNotExistError(contact_id=contact_id)
response_data = response.json()
return models.Contact.model_validate(response_data)

async def update(
Expand All @@ -80,16 +80,16 @@ async def update(
'public_name': public_name,
'is_hidden': is_hidden,
}
async with self._http_client.put(url, json=request_data) as response:
if response.status == 404:
raise ContactDoesNotExistError(contact_id=contact_id)
if response.status != 204:
raise ServerAPIError
response = await self._http_client.put(url, json=request_data)
if response.status_code == 404:
raise ContactDoesNotExistError(contact_id=contact_id)
if response.status_code != 204:
raise ServerAPIError

async def delete_by_id(self, contact_id: int) -> None:
url = f'/contacts/{contact_id}/'
async with self._http_client.delete(url) as response:
if response.status == 404:
raise ContactDoesNotExistError(contact_id=contact_id)
if response.status != 204:
raise ServerAPIError
response = await self._http_client.delete(url)
if response.status_code == 404:
raise ContactDoesNotExistError(contact_id=contact_id)
if response.status_code != 204:
raise ServerAPIError
8 changes: 4 additions & 4 deletions src/repositories/food_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
class FoodMenuRepository(APIRepository):

async def get_all(self) -> list[DailyFoodMenu]:
async with self._http_client.get('/food-menu/') as response:
if response.status != 200:
raise ServerAPIError
response_data = await response.json()
response = await self._http_client.get('/food-menu/')
if response.status_code != 200:
raise ServerAPIError
response_data = response.json()
type_adapter = TypeAdapter(list[DailyFoodMenu])
return type_adapter.validate_python(response_data['food_menus'])
9 changes: 4 additions & 5 deletions src/repositories/manas_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ class ManasIdRepository(APIRepository):
async def get_manas_id_by_user_id(self, user_id: int) -> ManasId:
url = f'/manas-id/user-id/{user_id}/'

async with self._http_client.get(url) as response:
if response.status == 404:
raise ManasIdDoesNotExistError(user_id)

response_data = await response.json()
response = await self._http_client.get(url)
if response.status_code == 404:
raise ManasIdDoesNotExistError(user_id)

response_data = response.json()
return ManasId.model_validate(response_data)
16 changes: 8 additions & 8 deletions src/repositories/secret_medias.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ async def create(
'name': description,
'contact_id': contact_id,
}
async with self._http_client.post(url, json=request_data) as response:
if response.status == 409:
raise SecretMediaAlreadyExistsError
response_data = await response.json()
response = await self._http_client.post(url, json=request_data)
if response.status_code == 409:
raise SecretMediaAlreadyExistsError
response_data = response.json()
return models.SecretMedia.model_validate(response_data)

async def get_by_id(self, secret_media_id: UUID) -> models.SecretMedia:
url = f'/secret-medias/{secret_media_id}/'
async with self._http_client.get(url) as response:
if response.status == 404:
raise SecretMediaDoesNotExistError
response_data = await response.json()
response = await self._http_client.get(url)
if response.status_code == 404:
raise SecretMediaDoesNotExistError
response_data = response.json()
return models.SecretMedia.model_validate(response_data)
11 changes: 5 additions & 6 deletions src/repositories/secret_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ async def create(
'text': text,
}
url = '/secret-messages/'
async with self._http_client.post(url, json=request_data):
pass
await self._http_client.post(url, json=request_data)

async def get_by_id(self, secret_message_id: UUID) -> models.SecretMessage:
url = f'/secret-messages/{str(secret_message_id)}/'
async with self._http_client.get(url) as response:
if response.status == 404:
raise SecretMessageDoesNotExistError
response_data = await response.json()
response = await self._http_client.get(url)
if response.status_code == 404:
raise SecretMessageDoesNotExistError
response_data = response.json()
return models.SecretMessage.model_validate(response_data)
Loading

0 comments on commit 48bf9da

Please sign in to comment.