1
from pathlib import Path
2
from typing import Optional
4
from fastapi import APIRouter, FastAPI, File, UploadFile
5
from fastapi.exceptions import HTTPException
6
from fastapi.testclient import TestClient
13
class ContentSizeLimitMiddleware:
14
"""Content size limiting middleware for ASGI applications
16
app (ASGI application): ASGI application
17
max_content_size (optional): the maximum content size allowed in bytes, None for no limit
20
def __init__(self, app: APIRouter, max_content_size: Optional[int] = None):
22
self.max_content_size = max_content_size
24
def receive_wrapper(self, receive):
29
message = await receive()
30
if message["type"] != "http.request":
31
return message # pragma: no cover
33
body_len = len(message.get("body", b""))
35
if received > self.max_content_size:
39
"name": "ContentSizeLimitExceeded",
41
"message": "File limit exceeded",
48
async def __call__(self, scope, receive, send):
49
if scope["type"] != "http" or self.max_content_size is None:
50
await self.app(scope, receive, send)
53
wrapper = self.receive_wrapper(receive)
54
await self.app(scope, wrapper, send)
57
@router.post("/middleware")
58
def run_middleware(file: UploadFile = File(..., description="Big File")):
59
return {"message": "OK"}
62
app.include_router(router)
63
app.add_middleware(ContentSizeLimitMiddleware, max_content_size=2**8)
66
client = TestClient(app)
69
def test_custom_middleware_exception(tmp_path: Path):
70
default_pydantic_max_size = 2**16
71
path = tmp_path / "test.txt"
72
path.write_bytes(b"x" * (default_pydantic_max_size + 1))
75
with open(path, "rb") as file:
76
response = client.post("/middleware", files={"file": file})
77
assert response.status_code == 422, response.text
78
assert response.json() == {
80
"name": "ContentSizeLimitExceeded",
82
"message": "File limit exceeded",
87
def test_custom_middleware_exception_not_raised(tmp_path: Path):
88
path = tmp_path / "test.txt"
89
path.write_bytes(b"<file content>")
92
with open(path, "rb") as file:
93
response = client.post("/middleware", files={"file": file})
94
assert response.status_code == 200, response.text
95
assert response.json() == {"message": "OK"}