Skip to content

Commit 756fa6a

Browse files
committed
Remove redundant session transactions
1 parent d5ce2c3 commit 756fa6a

File tree

5 files changed

+12
-40
lines changed

5 files changed

+12
-40
lines changed

docs/index.md

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -107,20 +107,19 @@ from sqlalchemy.ext.asyncio import (
107107

108108
DATABASE_URL = 'sqlite+aiosqlite:///db.sqlite3'
109109

110-
engine = create_async_engine(DATABASE_URL, future=True, echo=True)
110+
engine = create_async_engine(DATABASE_URL, echo=True)
111111

112112
AsyncSessionLocal = async_sessionmaker(
113-
autocommit=False,
114-
expire_on_commit=False,
115-
autoflush=True,
116113
bind=engine,
114+
expire_on_commit=False,
117115
class_=AsyncSession,
118116
)
119117

120118

121119
async def get_session() -> typing.AsyncGenerator[AsyncSession, None]:
122120
async with AsyncSessionLocal() as session:
123121
yield session
122+
124123
```
125124

126125
The last file before creating the routes is the `schemas.py`, which will contain all the [Pydantic](https://docs.pydantic.dev/latest/){:target="\_blank"} models.
@@ -197,8 +196,7 @@ SessionDep = Annotated[AsyncSession, Depends(get_session)]
197196
async def get_all_tickets(session: SessionDep):
198197
async with session.begin():
199198
tickets = await session.scalars(select(Ticket))
200-
201-
all_tickets = tickets.all()
199+
all_tickets = tickets.all()
202200

203201
return {'tickets': all_tickets}
204202

@@ -213,10 +211,6 @@ async def create_ticket(session: SessionDep, ticket_in: TicketRequestCreate):
213211

214212
async with session.begin():
215213
session.add(new_ticket)
216-
await session.commit()
217-
218-
async with session.begin():
219-
await session.refresh(new_ticket)
220214

221215
return new_ticket
222216

@@ -253,11 +247,6 @@ async def get_ticket_by_id(session: SessionDep, ticket_in: TicketRequestBuy):
253247
detail='Ticket has already been sold',
254248
)
255249

256-
await session.commit()
257-
258-
async with session.begin():
259-
await session.refresh(ticket_db)
260-
261250
return ticket_db
262251

263252
```
@@ -425,7 +414,6 @@ async def test_get_all_tickets_success(
425414

426415
async with async_session.begin():
427416
async_session.add_all(tickets)
428-
await async_session.commit()
429417

430418
response = await async_client.get('/tickets/all')
431419

@@ -438,6 +426,7 @@ async def test_get_all_tickets_when_empty(async_client: AsyncClient):
438426

439427
assert response.status_code == HTTPStatus.OK
440428
assert response.json()['tickets'] == []
429+
441430
```
442431

443432
In total there are 6 test, and the rest of them has the same logic. Their full implementations can be checked in the repository.

src/app.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,7 @@ async def lifespan(app: FastAPI):
3333
async def get_all_tickets(session: SessionDep):
3434
async with session.begin():
3535
tickets = await session.scalars(select(Ticket))
36-
37-
all_tickets = tickets.all()
36+
all_tickets = tickets.all()
3837

3938
return {'tickets': all_tickets}
4039

@@ -49,10 +48,6 @@ async def create_ticket(session: SessionDep, ticket_in: TicketRequestCreate):
4948

5049
async with session.begin():
5150
session.add(new_ticket)
52-
await session.commit()
53-
54-
async with session.begin():
55-
await session.refresh(new_ticket)
5651

5752
return new_ticket
5853

@@ -89,9 +84,4 @@ async def get_ticket_by_id(session: SessionDep, ticket_in: TicketRequestBuy):
8984
detail='Ticket has already been sold',
9085
)
9186

92-
await session.commit()
93-
94-
async with session.begin():
95-
await session.refresh(ticket_db)
96-
9787
return ticket_db

src/database.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,11 @@
88

99
DATABASE_URL = 'sqlite+aiosqlite:///db.sqlite3'
1010

11-
engine = create_async_engine(DATABASE_URL, future=True, echo=True)
11+
engine = create_async_engine(DATABASE_URL, echo=True)
1212

1313
AsyncSessionLocal = async_sessionmaker(
14-
autocommit=False,
15-
expire_on_commit=False,
16-
autoflush=True,
1714
bind=engine,
15+
expire_on_commit=False,
1816
class_=AsyncSession,
1917
)
2018

tests/conftest.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,15 @@ def anyio_backend() -> str:
2121

2222
@pytest.fixture(scope='session')
2323
def postgres_container(
24-
anyio_backend: typing.Literal['asyncio']
24+
anyio_backend: typing.Literal['asyncio'],
2525
) -> typing.Generator[PostgresContainer, None, None]:
2626
with PostgresContainer('postgres:16', driver='asyncpg') as postgres:
2727
yield postgres
2828

2929

3030
@pytest.fixture
3131
async def async_session(
32-
postgres_container: PostgresContainer
32+
postgres_container: PostgresContainer,
3333
) -> typing.AsyncGenerator[AsyncSession, None]:
3434
async_db_url = postgres_container.get_connection_url()
3535
async_engine = create_async_engine(async_db_url, pool_pre_ping=True)
@@ -39,10 +39,9 @@ async def async_session(
3939
await conn.run_sync(table_register.metadata.create_all)
4040

4141
async_session = async_sessionmaker(
42-
autoflush=False,
4342
bind=async_engine,
44-
class_=AsyncSession,
4543
expire_on_commit=False,
44+
class_=AsyncSession,
4645
)
4746

4847
async with async_session() as session:
@@ -53,7 +52,7 @@ async def async_session(
5352

5453
@pytest.fixture
5554
async def async_client(
56-
async_session: AsyncSession
55+
async_session: AsyncSession,
5756
) -> typing.AsyncGenerator[AsyncClient, None]:
5857
app.dependency_overrides[get_session] = lambda: async_session
5958
_transport = ASGITransport(app=app)

tests/test_routes.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ async def test_get_all_tickets_success(
2121

2222
async with async_session.begin():
2323
async_session.add_all(tickets)
24-
await async_session.commit()
2524

2625
response = await async_client.get('/tickets/all')
2726

@@ -60,7 +59,6 @@ async def test_buy_ticket_success(
6059

6160
async with async_session.begin():
6261
async_session.add(new_ticket)
63-
await async_session.commit()
6462

6563
response = await async_client.post(
6664
'/tickets/buy',
@@ -83,7 +81,6 @@ async def test_buy_ticket_when_ticket_not_found(
8381

8482
async with async_session.begin():
8583
async_session.add(new_ticket)
86-
await async_session.commit()
8784

8885
response = await async_client.post(
8986
'/tickets/buy',
@@ -101,7 +98,6 @@ async def test_buy_ticket_when_already_sold(
10198

10299
async with async_session.begin():
103100
async_session.add(new_ticket)
104-
await async_session.commit()
105101

106102
response = await async_client.post(
107103
'/tickets/buy', json={'ticket_id': new_ticket.id, 'user': 'other user'}

0 commit comments

Comments
 (0)