Skip to content

Commit d8de41c

Browse files
authored
Non-Blocking starlette body read (#633)
1 parent 1156738 commit d8de41c

File tree

3 files changed

+7
-9
lines changed

3 files changed

+7
-9
lines changed

api/main.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,25 +84,21 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
8484

8585
@app.exception_handler(StarletteHTTPException)
8686
async def http_exception_handler(request, exc):
87-
await log_exception(request, exc, body='StarletteHTTPException handler cannot read body atm. Waiting for FastAPI upgrade.', details=exc.detail)
87+
body = await request.body()
88+
await log_exception(request, exc, body=body, details=exc.detail)
8889
return ORJSONResponse(
8990
status_code=exc.status_code,
9091
content=jsonable_encoder({'success': False, 'err': exc.detail}),
9192
)
9293

9394
async def catch_exceptions_middleware(request: Request, call_next):
9495
#pylint: disable=broad-except
96+
body = None
9597
try:
98+
body = await request.body()
9699
return await call_next(request)
97100
except Exception as exc:
98-
# body = await request.body() # This blocks the application. Unclear atm how to handle it properly
99-
# seems like a bug: https://github.com/tiangolo/fastapi/issues/394
100-
# Although the issue is closed the "solution" still behaves with same failure
101-
# Actually Starlette, the underlying library to FastAPI has already introduced this functionality:
102-
# https://github.com/encode/starlette/pull/1692
103-
# However FastAPI does not support the new Starlette 0.31.1
104-
# The PR relevant here is: https://github.com/tiangolo/fastapi/pull/9939
105-
await log_exception(request, exc, body='Middleware cannot read body atm. Waiting for FastAPI upgrade')
101+
await log_exception(request, exc, body=body)
106102
return ORJSONResponse(
107103
content={
108104
'success': False,

docker/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
gunicorn==21.2.0
22
psycopg[binary]==3.1.16
33
fastapi==0.108.0
4+
starlette>=0.32
45
uvicorn[standard]==0.25.0
56
pandas==2.1.4
67
PyYAML==6.0.1

requirements-dev.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pytest==7.4.3
44
requests==2.31.0
55
pylint==3.0.3
66
fastapi==0.108.0
7+
starlette>=0.32
78
anybadge==1.14.0
89

910
# just to clear the pylint errors for the files in /api

0 commit comments

Comments
 (0)