|
| 1 | +# Created by ChatGPT (GPT-3.5) |
| 2 | +# REF: https://chat.openai.com/share/4ab741e7-8059-4be1-b3da-46b8e78d98cc |
| 3 | +# REF: https://gealber.com/gzip-middleware-fastapi |
| 4 | +import gzip |
| 5 | +import json |
| 6 | +from starlette.types import Message |
| 7 | +from starlette.requests import Request |
| 8 | +from starlette.responses import JSONResponse |
| 9 | +from starlette.middleware.base import BaseHTTPMiddleware |
| 10 | + |
| 11 | + |
| 12 | +class GZipRequestMiddleware(BaseHTTPMiddleware): |
| 13 | + async def set_body(self, request: Request): |
| 14 | + receive_ = await request._receive() |
| 15 | + content_encoding = request.headers.get('Content-Encoding', '').lower() |
| 16 | + print("content_encoding", content_encoding) |
| 17 | + if 'gzip' in content_encoding: |
| 18 | + print("receive_", receive_) |
| 19 | + |
| 20 | + try: |
| 21 | + content_length = int( |
| 22 | + request.headers.get('Content-Length', '0')) |
| 23 | + body = receive_.get('body') |
| 24 | + if len(body) != content_length: |
| 25 | + return JSONResponse( |
| 26 | + content={"error": "Invalid Content-Length header"}, |
| 27 | + status_code=400, |
| 28 | + ) |
| 29 | + json_byte_string = gzip.decompress(body) |
| 30 | + # json_string = json_byte_string.decode('utf-8') |
| 31 | + # json_object = json.dumps(json_string) |
| 32 | + receive_['body'] = json_byte_string |
| 33 | + print("content_length", content_length) |
| 34 | + print("body", body) |
| 35 | + print("receive_['body']", receive_['body']) |
| 36 | + except ValueError: |
| 37 | + return JSONResponse( |
| 38 | + content={"error": "Invalid Content-Length header"}, |
| 39 | + status_code=400, |
| 40 | + ) |
| 41 | + except Exception as e: |
| 42 | + print(e) |
| 43 | + return JSONResponse( |
| 44 | + content={"error": "Failed to decompress gzip content"}, |
| 45 | + status_code=400, |
| 46 | + ) |
| 47 | + |
| 48 | + async def receive() -> Message: |
| 49 | + return receive_ |
| 50 | + |
| 51 | + request._receive = receive |
| 52 | + |
| 53 | + async def dispatch(self, request, call_next): |
| 54 | + await self.set_body(request) |
| 55 | + response = await call_next(request) |
| 56 | + return response |
0 commit comments