Skip to content

Commit 063ddc7

Browse files
feat: adding dbsessionmiddleware a status_code verification
1 parent b801e98 commit 063ddc7

1 file changed

Lines changed: 18 additions & 2 deletions

File tree

jsweb/middleware.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,24 @@ async def __call__(self, scope, receive, send):
175175

176176
from .database import db_session
177177
try:
178-
await self.app(scope, receive, send)
179-
db_session.commit()
178+
status_code = None
179+
180+
async def send_wrapper(message):
181+
nonlocal status_code
182+
if message["type"] == "http.response.start":
183+
status_code = message["status"]
184+
await send(message )
185+
186+
await self.app(scope, receive, send_wrapper)
187+
188+
# Commit only if the response status code is a success (2xx)
189+
# If status_code is None, it means no response was sent, which is an error state
190+
# or a successful response that didn't send headers yet (unlikely in a standard flow).
191+
# It's safer to rollback if status_code is not set or is not 2xx.
192+
if status_code is not None and 200 <= status_code < 300:
193+
db_session.commit()
194+
else:
195+
db_session.rollback()
180196
except Exception:
181197
db_session.rollback()
182198
raise

0 commit comments

Comments
 (0)