Skip to content

Commit

Permalink
Add support to brotli compress (#140)
Browse files Browse the repository at this point in the history
* Add support to brotli compress
  • Loading branch information
fullonic authored Sep 30, 2020
1 parent dc16f7f commit 7874f70
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
2 changes: 1 addition & 1 deletion mangum/protocols/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ async def send(self, message: Message) -> None:
if (
mimetype not in self.text_mime_types
and not mimetype.startswith("text/")
) or self.response["headers"].get("content-encoding") == "gzip":
) or self.response["headers"].get("content-encoding") in ["gzip", "br"]:
body = base64.b64encode(body)
self.response["isBase64Encoded"] = True

Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ starlette
quart; python_version == '3.7'
moto
mypy

brotli
brotli-asgi
# Docs
mkdocs
mkdocs-material
32 changes: 31 additions & 1 deletion tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
import urllib.parse

import pytest
import brotli
from brotli_asgi import BrotliMiddleware
from starlette.applications import Starlette
from starlette.middleware.gzip import GZipMiddleware
from starlette.responses import PlainTextResponse

from mangum import Mangum


Expand Down Expand Up @@ -711,3 +712,32 @@ async def app(scope, receive, send):
if expected_multi_value_headers:
expected["multiValueHeaders"] = expected_multi_value_headers
assert response == expected


@pytest.mark.parametrize("mock_http_event", [["GET", "", None]], indirect=True)
def test_http_binary_br_response(mock_http_event) -> None:
body = json.dumps({"abc": "defg"})

async def app(scope, receive, send):
assert scope["type"] == "http"
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [[b"content-type", b"application/json"]],
}
)

await send({"type": "http.response.body", "body": body.encode()})

handler = Mangum(BrotliMiddleware(app, minimum_size=1), lifespan="off")
response = handler(mock_http_event, {})

assert response["isBase64Encoded"]
assert response["headers"] == {
"content-encoding": "br",
"content-type": "application/json",
"content-length": "19",
"vary": "Accept-Encoding",
}
assert response["body"] == base64.b64encode(brotli.compress(body.encode())).decode()

0 comments on commit 7874f70

Please sign in to comment.