Problems with FastAPI/Starlette Gzip middleware
See original GitHub issue(First off, awesome package. Being able to use an actual framework on Lambda without writing any ‘transformation’ code myself has been incredible.)
I’m attempting to use Starlette’s GZipMiddleware
with FastAPI right now, and our front-end is sending a accept-encoding: gzip, deflate, br
header.
When I configure the middleware like so…
APP = FastAPI()
# ... other middleware
APP.add_middleware(
GZipMiddleware,
minimum_size=512,
)
HANDLER = Mangum(APP, enable_lifespan=False)
… I receive the following error.
Exception in ASGI application
Traceback (most recent call last):
File "/var/task/mangum/protocols/http.py", line 39, in run
await app(self.scope, self.receive, self.send)
File "/var/task/fastapi/applications.py", line 142, in __call__
await super().__call__(scope, receive, send) # pragma: no cover
File "/var/task/starlette/applications.py", line 134, in __call__
await self.error_middleware(scope, receive, send)
File "/var/task/starlette/middleware/errors.py", line 178, in __call__
raise exc from None
File "/var/task/starlette/middleware/errors.py", line 156, in __call__
await self.app(scope, receive, _send)
File "/var/task/starlette/middleware/base.py", line 26, in __call__
await response(scope, receive, send)
File "/var/task/starlette/responses.py", line 200, in __call__
await send({"type": "http.response.body", "body": b"", "more_body": False})
File "/var/task/starlette/middleware/errors.py", line 153, in _send
await send(message)
File "/var/task/mangum/protocols/http.py", line 97, in send
self.response["body"] = body.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
I had initially thought it might be due to the minimum_size
parameter but removing that did not work. If I removed the middleware completely then my Lambda works perfectly fine.
I’m a little confused by the "body": b""
part, since this Lambda is returning data, and when I test locally running the same APP
with uvicorn
I have no issues - body is compressed and status code is 200.
Is there something I need to do to configure Mangum for compression? Am I reading the stack trace wrong?
** FastAPI 0.48.0 Mangum 0.7.0 Python 3.6.8
Issue Analytics
- State:
- Created 4 years ago
- Comments:15 (8 by maintainers)
Just released 0.7.5. This should resolve the gzip issues, and your issue @sses79 (see the README for including your content type in the
text_mime_types
list).If there are any problems feel free to comment here and I’ll reopen.
@burritoIand I merged in @lsorber’s PR, but I’m going to make sure the gzip responses are working/tested before I push the next release. Any additional details you could provide would be very helpful (especially an example AWS event or any error tracebacks).