Skip to content

Commit dd382ef

Browse files
committed
refactor: update database session management in authentication and router setup
1 parent 5a86454 commit dd382ef

4 files changed

Lines changed: 19 additions & 31 deletions

File tree

app/main.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
async def lifespan(app: FastAPI):
1414
# add check db file and create if not found
1515
await init_db()
16-
app.db_session_factory = AsyncSessionLocal
16+
app.db_session_factory = AsyncSessionLocal()
1717
try:
1818
yield
1919
finally:
@@ -27,11 +27,6 @@ async def lifespan(app: FastAPI):
2727
)
2828

2929

30-
async def get_db_session():
31-
# Usa app.attr para acessar a fábrica de sessões que foi injetada
32-
async with app.db_session_factory() as session:
33-
yield session
34-
35-
app.include_router(setup_router_v2(get_db_session), prefix="/api")
30+
app.include_router(setup_router_v2(), prefix="/api")
3631

3732
logger.info("PyNews Server Starter")

app/routers/authentication.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from fastapi import APIRouter, Depends, HTTPException, status
1+
from fastapi import APIRouter, Depends, HTTPException, status, Request
22
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
33
from sqlmodel.ext.asyncio.session import AsyncSession
44
import jwt
@@ -11,13 +11,13 @@
1111

1212
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/authentication/token")
1313

14-
def setup(get_db_session_dep):
14+
def setup():
1515
router = APIRouter(prefix='/authentication', tags=['authentication'])
16-
async def authenticate_community(username: str, password: str, session: AsyncSession = Depends(get_db_session_dep)):
16+
async def authenticate_community(request: Request , username: str, password: str):
1717
# Valida se o usuário existe e se a senha está correta
1818
found_community = await get_community_by_username(
1919
username=username,
20-
session=session
20+
session=request.app.db_session_factory
2121
)
2222
if not found_community or not auth.verify_password(password, found_community.password):
2323
return None
@@ -27,20 +27,21 @@ async def authenticate_community(username: str, password: str, session: AsyncSes
2727
#### Teste
2828

2929
@router.post("/create_commumity")
30-
async def create_community( session: AsyncSession = Depends(get_db_session_dep)):
30+
async def create_community(request: Request ):
3131
password = "123Asd!@#"
3232
hashed_password=auth.hash_password(password)
3333
community = DBCommunity(username="username", email="username@test.com", password=hashed_password)
34+
session = request.app.db_session_factory
3435
session.add(community)
3536
await session.commit()
3637
await session.refresh(community)
3738
return {'msg':'succes? '}
3839
#### Teste
3940

4041
@router.post("/token", response_model=Token)
41-
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), session: AsyncSession = Depends(get_db_session_dep)) :
42+
async def login_for_access_token(request: Request , form_data: OAuth2PasswordRequestForm = Depends() ) :
4243
# Rota de login: valida credenciais e retorna token JWT
43-
community = await authenticate_community(form_data.username, form_data.password, session)
44+
community = await authenticate_community(form_data.username, form_data.password, request.app.db_session_factory)
4445
if not community:
4546
raise HTTPException(
4647
status_code=status.HTTP_401_UNAUTHORIZED,

app/routers/router.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
from app.routers.news.routes import setup as news_router_setup
55
from app.routers.authentication import setup as authentication_router_setup
66

7-
def setup_router(get_db_session_dep) -> APIRouter:
7+
def setup_router() -> APIRouter:
88
router = APIRouter()
99
router.include_router(healthcheck_router_setup(), prefix="")
1010
router.include_router(news_router_setup(), prefix="")
11-
router.include_router(authentication_router_setup(get_db_session_dep), prefix='')
11+
router.include_router(authentication_router_setup(), prefix='')
1212
return router

tests/conftest.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
from sqlmodel import SQLModel
1010
from sqlmodel.ext.asyncio.session import AsyncSession
1111

12-
from app.main import app as fastapi_app
13-
from app.main import get_db_session
12+
from app.main import app
13+
#from app.main import get_db_session
1414

1515
# Importar todos os modelos SQLModel a serem usados
1616
# (necessários para as validações de modelo)
@@ -50,19 +50,11 @@ async def session() -> AsyncGenerator[AsyncSession, None]:
5050
yield session
5151
await session.close()
5252

53-
54-
@pytest.fixture
55-
def test_app() -> Generator[FastAPI]:
56-
# Create a mock schema checker
57-
mock_schema_checker = AsyncMock()
58-
mock_schema_checker.validate = AsyncMock(return_value=None)
59-
mock_schema_checker.start = AsyncMock(return_value=None)
60-
61-
# Add the mock to the app
62-
fastapi_app.schema_checker = mock_schema_checker
63-
fastapi_app.dependency_overrides[get_db_session] = get_db_session_test
64-
yield fastapi_app
65-
fastapi_app.dependency_overrides.clear()
53+
@pytest_asyncio.fixture
54+
async def test_app(session) -> FastAPI:
55+
mock_db_connection = session
56+
setattr(app, 'db_session_factory', mock_db_connection)
57+
return app
6658

6759

6860
@pytest_asyncio.fixture(scope="function")

0 commit comments

Comments
 (0)