|
1 | 1 | """Utilities for middleware response handling.""" |
2 | 2 |
|
3 | | -import gzip |
4 | 3 | import json |
5 | 4 | import re |
6 | | -import zlib |
7 | 5 | from abc import ABC, abstractmethod |
8 | 6 | from typing import Any, Optional |
9 | 7 |
|
10 | | -import brotli |
11 | 8 | from starlette.datastructures import Headers, MutableHeaders |
12 | 9 | from starlette.requests import Request |
13 | 10 | from starlette.types import ASGIApp, Message, Receive, Scope, Send |
14 | 11 |
|
15 | | -# TODO: Consider using a single middleware to handle all compression/decompression |
16 | | -ENCODING_HANDLERS = { |
17 | | - "gzip": gzip, |
18 | | - "deflate": zlib, |
19 | | - "br": brotli, |
20 | | -} |
21 | | - |
22 | 12 |
|
23 | 13 | class JsonResponseMiddleware(ABC): |
24 | 14 | """Base class for middleware that transforms JSON response bodies.""" |
@@ -89,32 +79,17 @@ async def process_message(message: Message) -> None: |
89 | 79 | body += message["body"] |
90 | 80 |
|
91 | 81 | # Skip body chunks until all chunks have been received |
92 | | - if message["more_body"]: |
| 82 | + if message.get("more_body"): |
93 | 83 | return |
94 | 84 |
|
95 | | - # Handle compression/decompression |
96 | 85 | headers = MutableHeaders(scope=start_message) |
97 | | - content_encoding = headers.get("content-encoding", "").lower() |
98 | | - handler = None |
99 | | - if content_encoding: |
100 | | - handler = ENCODING_HANDLERS.get(content_encoding) |
101 | | - assert handler, f"Unsupported content encoding: {content_encoding}" |
102 | | - body = ( |
103 | | - handler.decompress(body) |
104 | | - if content_encoding != "deflate" |
105 | | - else handler.decompress(body, -zlib.MAX_WBITS) |
106 | | - ) |
107 | 86 |
|
108 | 87 | # Transform the JSON body |
109 | 88 | if body: |
110 | 89 | data = json.loads(body) |
111 | 90 | transformed = self.transform_json(data) |
112 | 91 | body = json.dumps(transformed).encode() |
113 | 92 |
|
114 | | - # Re-compress if necessary |
115 | | - if handler: |
116 | | - body = handler.compress(body) |
117 | | - |
118 | 93 | # Update content-length header |
119 | 94 | headers["content-length"] = str(len(body)) |
120 | 95 | assert start_message, "Expected start_message to be set" |
|
0 commit comments