Skip to content

Commit fac9bcb

Browse files
author
reinhud
committed
Fixed bug where async session was not yieleded correctly
1 parent 0f599f4 commit fac9bcb

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+58
-65
lines changed

README.md

Lines changed: 19 additions & 17 deletions

src/docker-compose.yml

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ services:
1111
volumes: # dont use this in production, mounting docker volume to location on my machine where to store postgres data for docker
1212
- ./docker_pg_data/postgres-data:/var/lib/postgresql/data
1313
env_file:
14-
- prod.env
14+
- .env
1515
networks:
1616
app1_net:
1717
ipv4_address: 192.168.0.2
@@ -26,7 +26,7 @@ services:
2626
volumes:
2727
- ./docker_pg_data/pgadmin-data:/var/lib/pgadmin
2828
env_file:
29-
- prod.env
29+
- .env
3030
depends_on:
3131
- db
3232
networks:
@@ -37,19 +37,16 @@ services:
3737
fastapi_server:
3838
container_name: fastapi_server_container
3939
build:
40-
context: ./microservices/fastapi_server
40+
context: ./fastapi_server
4141
dockerfile: Dockerfile
4242
working_dir: /fastapi_server
4343
ports:
4444
- "8001:8001"
45-
command: >
46-
bash -c "uvicorn app.fastapi_server:app --reload --workers 1 --host 0.0.0.0 --port 8001
47-
&& alembic revision --autogenerate -m "Current DB state"
48-
&& alembic upgrade head"
45+
command: bash -c "uvicorn app.fastapi_server:app --reload --workers 1 --host 0.0.0.0 --port 8001"
4946
volumes:
50-
- ./microservices/fastapi_server:/fastapi_server # used for live reloading of container to changes in app on local machine
47+
- ./fastapi_server:/fastapi_server # used for live reloading of container to changes in app on local machine
5148
env_file:
52-
- prod.env
49+
- .env
5350
depends_on:
5451
- db
5552
networks:

src/microservices/fastapi_server/app/api/dependencies/database.py renamed to src/fastapi_server/app/api/dependencies/database.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,20 @@ async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
2020
All conversations with the database are established via the session
2121
objects. Also. the sessions act as holding zone for ORM-mapped objects.
2222
"""
23-
async_Session = sessionmaker(
23+
logger.warning("Trying to get async engine")
24+
async_session = sessionmaker(
2425
bind=get_async_engine(),
2526
class_=AsyncSession,
2627
autoflush=False,
2728
expire_on_commit=False, # document this
2829
)
29-
async with async_Session as a_sess:
30+
logger.warning("Success with async engine")
31+
async with async_session() as async_sess:
32+
logger.warning("In session loop")
3033
try:
31-
yield a_sess
34+
yield async_sess
35+
logger.warning("yielded session")
3236
except SQLAlchemyError as e:
3337
logger.error("Unable to yield session in database dependency")
3438
logger.error(e)
35-
36-
37-
39+

src/microservices/fastapi_server/app/api/dependencies/repository.py renamed to src/fastapi_server/app/api/dependencies/repository.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
TODO:
44
1. do funcs need to be async?
55
"""
6-
from typing import Callable, Type
6+
from typing import Callable, Type, TypeVar
77

88
from fastapi import Depends
99
from sqlalchemy.ext.asyncio import AsyncSession
1010

11-
from app._utils._types import SQLA_REPO_TYPE
1211
from app.api.dependencies.database import get_async_session
12+
from app.db.repositories.base import SQLAlchemyRepository
13+
14+
SQLA_REPO_TYPE = TypeVar("SQLA_REPO_TYPE", bound=SQLAlchemyRepository)
1315

1416

1517
# Repo dependency

src/microservices/fastapi_server/app/db/db_session.py renamed to src/fastapi_server/app/db/db_session.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,3 @@ def get_async_engine() -> AsyncEngine:
1515
return async_engine
1616

1717

18-
19-

src/microservices/fastapi_server/app/db/repositories/base.py renamed to src/fastapi_server/app/db/repositories/base.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
11
"""Abstract CRUD Repo definitions."""
22
from abc import ABC
3-
from typing import List
3+
from typing import List, TypeVar
44

55
from loguru import logger
66
from sqlalchemy import select
77
from sqlalchemy.ext.asyncio import AsyncSession
88

9-
from app._utils._types import CREATE_SCHEMA, READ_MULTIPLE_SCHEMA, SQLA_MODEL
10-
from app.db.models.base import BaseSaModel
9+
from app.db.models.base import Base
1110
from app.models.base import BaseSchema
1211

12+
## ===== Custom Type Hints ===== ##
13+
# sqlalchemy models
14+
SQLA_MODEL = TypeVar("SQLA_MODEL", bound=Base)
1315

16+
# pydantic models
17+
CREATE_SCHEMA = TypeVar("CREATE_SCHEMA", bound=BaseSchema)
18+
READ_MULTIPLE_SCHEMA = TypeVar("READ_MULTIPLE_SCHEMA", bound=BaseSchema)
19+
20+
21+
## ===== CRUD Repo ===== ##
1422
class SQLAlchemyRepository(ABC):
1523
"""Abstract SQLAlchemy repo defining basic database operations.
1624
@@ -24,15 +32,15 @@ def __init__(
2432
self.db = db
2533

2634
# models and schemas object instanziation and validation
27-
sqla_model: SQLA_MODEL
35+
sqla_model = SQLA_MODEL
2836

29-
create_Schema: CREATE_SCHEMA
30-
read_multiple_schema: READ_MULTIPLE_SCHEMA
37+
create_schema = CREATE_SCHEMA
38+
read_multiple_schema = READ_MULTIPLE_SCHEMA
3139

3240
## ===== Basic Crud Operations ===== ##
3341
async def create(
3442
self,
35-
obj_new: create_Schema
43+
obj_new: create_schema
3644
) -> sqla_model | None:
3745
"""Commit new object to the database."""
3846
try:

src/microservices/fastapi_server/app/db/repositories/user.py renamed to src/fastapi_server/app/db/repositories/user.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class UserRepository(SQLAlchemyRepository):
1616
"""
1717
sqla_model = UserModel
1818

19-
create_Schema = UserCreate
19+
create_schema = UserCreate
2020
read_multiple_schema = UserQueryOptionalSchema
2121

2222

src/microservices/fastapi_server/tests/test_api/test_routes/test_user.py renamed to src/fastapi_server/tests/test_api/test_routes/test_user.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""Testing user endpoints.
22
33
More like unit tests, we're mocking the actual database calls here.
4+
5+
TODO:
6+
1. Implement method to test 'read_multiple' asserting streaming results
47
"""
58
from fastapi import status
69
from fastapi.encoders import jsonable_encoder
@@ -73,10 +76,10 @@ async def test_read_multiple_users_OK(
7376

7477
async def mock_read_optional(self, query_schema):
7578
return Users_Output
76-
monkeypatch.setattr(SQLAlchemyRepository, "read_optional", mock_read_optional)
79+
monkeypatch.setattr(SQLAlchemyRepository, "read_multiple", mock_read_optional)
7780

7881
res = await async_test_client.post(
79-
"/api/user/get_optional",
82+
"/api/user/get_multiple",
8083
json=query_schema
8184
)
8285

src/microservices/fastapi_server/app/_utils/_types.py

Lines changed: 0 additions & 19 deletions
This file was deleted.

0 commit comments

Comments
 (0)