mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2025-12-28 12:32:59 +03:00
remove redundant objects, add nested injection
This commit is contained in:
parent
3be88902e5
commit
bb20c403fe
|
|
@ -1,3 +1,4 @@
|
|||
import asyncio
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI
|
||||
|
|
@ -5,8 +6,6 @@ from fastapi import Depends, FastAPI
|
|||
from dependency_injector import containers, providers
|
||||
from dependency_injector.wiring import Closing, Provide, inject
|
||||
|
||||
global_list = []
|
||||
|
||||
|
||||
class AsyncSessionLocal:
|
||||
def __init__(self):
|
||||
|
|
@ -20,23 +19,35 @@ class AsyncSessionLocal:
|
|||
print("Closing session !")
|
||||
|
||||
async def execute(self, user_input):
|
||||
await asyncio.sleep(0.1)
|
||||
return f"Executing {user_input} in session {self.id}"
|
||||
|
||||
|
||||
class APIRepository:
|
||||
@inject
|
||||
async def execute(self, user_input, db_session: AsyncSessionLocal = Provide["db_session"]):
|
||||
return await db_session.execute(user_input)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Container(containers.DeclarativeContainer):
|
||||
db_session = providers.ContextLocalResource(AsyncSessionLocal)
|
||||
api_repository = providers.Factory(APIRepository)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
@inject
|
||||
async def index(db: AsyncSessionLocal = Depends(Closing[Provide["db_session"]])):
|
||||
if db.id in global_list:
|
||||
raise Exception("The db session is already used") # never reaches here
|
||||
global_list.append(db.id)
|
||||
res = await db.execute("SELECT 1")
|
||||
async def index(
|
||||
db: AsyncSessionLocal = Depends(Closing[Provide["db_session"]]),
|
||||
api_repository: APIRepository = Depends(Provide["api_repository"]),
|
||||
):
|
||||
user_input = "SELECT 1"
|
||||
res = await db.execute(user_input)
|
||||
res_from_repo = await api_repository.execute(user_input=user_input)
|
||||
assert res == res_from_repo
|
||||
|
||||
return str(res)
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user