Skip to content

Commit 6ec947b

Browse files
authored
패키지 이름 변경, MongoDB 추가. (#2)
* Fix type hinting.. * Set current task.. * Add set extras.. * Fix async iterator.. * Fix base package name..
1 parent 84c803d commit 6ec947b

10 files changed

Lines changed: 362 additions & 13 deletions

File tree

poetry.lock

Lines changed: 288 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

py_mf_data/connections/motor.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from motor.motor_asyncio import AsyncIOMotorClient
2+
from typing import Union
3+
4+
5+
class AsyncMotor:
6+
def __init__(self, db_name, db_uri: str) -> None:
7+
self._db_uri = db_uri
8+
self.db_name = db_name
9+
self.client: Union[AsyncIOMotorClient, None] = None
10+
11+
async def connect(self):
12+
self.client = AsyncIOMotorClient(self._db_uri)
13+
14+
async def disconnect(self):
15+
self.client.close()
Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
from contextlib import asynccontextmanager, AbstractAsyncContextManager, AbstractContextManager, contextmanager
2-
from typing import Callable, Union
1+
from asyncio import current_task
2+
from contextlib import asynccontextmanager, contextmanager
3+
from typing import AsyncIterator, Callable, Iterator, Union
34

45
from sqlalchemy.engine import Engine, create_engine
56
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_scoped_session, create_async_engine
@@ -22,13 +23,14 @@ async def create_database(self) -> None:
2223
async def connect(self):
2324
self._engine = create_async_engine(self._db_uri, echo=True)
2425
self._session_factory = async_scoped_session(
25-
sessionmaker(autocommit=False, autoflush=False, bind=self._engine, class_=AsyncSession))
26+
sessionmaker(autocommit=False, autoflush=False, bind=self._engine, class_=AsyncSession),
27+
scopefunc=current_task)
2628

2729
async def disconnect(self):
2830
await self._engine.dispose()
2931

3032
@asynccontextmanager
31-
async def session(self) -> Callable[..., AbstractAsyncContextManager[AsyncSession]]:
33+
async def session(self) -> Callable[..., AsyncIterator[AsyncSession]]:
3234
session: AsyncSession = self._session_factory()
3335
try:
3436
yield session
@@ -56,7 +58,7 @@ def disconnect(self):
5658
self._engine.dispose()
5759

5860
@contextmanager
59-
def session(self) -> Callable[..., AbstractContextManager[Session]]:
61+
def session(self) -> Callable[..., Iterator[Session]]:
6062
session: Session = self._session_factory()
6163
try:
6264
yield session

py_mf_data/repositories/motor.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from abc import ABC
2+
from bson import ObjectId
3+
from typing import final
4+
5+
from py_mf_data.connections.motor import AsyncMotor
6+
from py_mf_data.errors import NotFoundException
7+
8+
9+
class AsyncRepository(ABC):
10+
def __init__(self, collection_name: str, motor: AsyncMotor) -> None:
11+
self._collection = motor.client[motor.db_name][collection_name]
12+
13+
@final
14+
async def delete_by_id(self, item_id: str):
15+
row = await self._collection.delete_one({"_id": ObjectId(item_id)})
16+
if not row:
17+
raise NotFoundException()
18+
19+
@final
20+
async def find_all(self):
21+
cursor = self._collection.find()
22+
results = list(map(lambda item: item, await cursor.to_list(length=100)))
23+
24+
return results
25+
26+
@final
27+
async def find_by_id(self, item_id: str):
28+
row = await self._collection.find_one({"_id": ObjectId(item_id)})
29+
if not row:
30+
raise NotFoundException()
31+
32+
return row
33+
34+
@final
35+
async def save(self, req: dict):
36+
return await self._collection.insert_one(req)
37+
38+
@final
39+
async def update_by_id(self, item_id: str, req: dict):
40+
await self._collection.update_one({"_id": ObjectId(item_id)}, req)
41+
return await self.find_by_id(item_id)
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
from abc import ABC, abstractmethod
22
from contextlib import AbstractAsyncContextManager, AbstractContextManager
3-
from typing import Callable, final, Iterator, Type, TypeVar
3+
from typing import AsyncIterator, Callable, final, Iterator, Type, TypeVar
44
from sqlalchemy.ext.asyncio import AsyncSession
55
from sqlalchemy.future import select
66
from sqlalchemy.orm import Session, Query
77
from sqlalchemy.sql.selectable import Select
88

9-
from fastapi_data.connections.sqlalchemy import Base
10-
from fastapi_data.errors import NotFoundException
9+
from py_mf_data.connections.sqlalchemy import Base
10+
from py_mf_data.errors import NotFoundException
1111

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

@@ -40,7 +40,7 @@ def _gen_stmt_for_param(self, **kwargs) -> Select:
4040
return stmt
4141

4242
@final
43-
async def find_all(self, **kwargs) -> Iterator[Type[ModelType]]:
43+
async def find_all(self, **kwargs) -> AsyncIterator[Type[ModelType]]:
4444
session: AsyncSession
4545
async with self._session_factory() as session:
4646
stmt = self._gen_stmt_for_param(**kwargs)

pyproject.toml

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,15 @@ authors = ["Neon K.I.D <contact@neonkid.xyz>"]
66

77
[tool.poetry.dependencies]
88
python = "^3.8"
9-
SQLAlchemy = "1.4.22"
9+
motor = {version = "2.5.1", optional = true}
10+
SQLAlchemy = {version = "1.4.22", optional = true}
1011

1112
[tool.poetry.dev-dependencies]
13+
pytest = "^6.2.4"
14+
15+
[tool.poetry.extras]
16+
mongodb = ["motor"]
17+
sql = ["SQLAlchemy"]
1218

1319
[build-system]
1420
requires = ["poetry-core>=1.0.0"]

0 commit comments

Comments
 (0)