Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rest request gzip decompress #950

Merged
merged 2 commits into from
Jan 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ eggs/
.tox
build/
dist/
venv/

# Notebook Checkpoints
.ipynb_checkpoints
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ eggs/
.tox
build/
dist/
venv/

# Notebook Checkpoints
.ipynb_checkpoints
Expand Down
2 changes: 1 addition & 1 deletion mlserver/rest/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def create_app(
default_response_class=Response,
exception_handlers=_EXCEPTION_HANDLERS, # type: ignore
)

app.router.route_class = APIRoute
app.add_middleware(GZipMiddleware)
if settings.cors_settings is not None:
app.add_middleware(
Expand Down
9 changes: 8 additions & 1 deletion mlserver/rest/requests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Any

from gzip import decompress as gzip_decompress
from fastapi import Request as _Request

try:
Expand All @@ -13,6 +13,13 @@ class Request(_Request):
Custom request class which uses `orjson` if present.
Otherwise, it falls back to the standard FastAPI request.
"""
async def body(self) -> bytes:
if not hasattr(self, "_body"):
body = await super().body()
if "gzip" in self.headers.getlist("Content-Encoding"):
body = gzip_decompress(body)
self._body = body
return self._body

async def json(self) -> Any:
if orjson is None:
Expand Down
15 changes: 14 additions & 1 deletion tests/rest/test_custom.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from mlserver.types import InferenceRequest

import gzip
import json

async def test_custom_handler(
rest_client,
Expand All @@ -11,6 +12,18 @@ async def test_custom_handler(
assert response.json() == 10


async def test_custom_handler_gzip(rest_client, inference_request: InferenceRequest):
response = await rest_client.post(
"/my-custom-endpoint",
content = gzip.compress(json.dumps([1, 2, 3, 4]).encode('utf-8')),
headers = {
"Content-Encoding": "gzip",
}
)

assert response.status_code == 200
assert response.json() == 10

async def test_gzip_compression(
rest_client,
inference_request,
Expand Down