-
|
Could someone verify if this is the right thing to do? It works as expected but I wanted to ensure that there are no pitfalls to this approach. import pathlib
import fastapi
import starlette.types as types
import starlette.responses as responses
class StaticRedirectMiddleware:
def __init__(self, app: fastapi.FastAPI, static_dir: pathlib.Path):
self.app: fastapi.FastAPI = app
self.static_dir: pathlib.Path = static_dir
async def __call__(self, scope: types.Scope, receive: types.Receive, send: types.Send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
response_sent = False
async def send_wrapper(message: types.Message):
nonlocal response_sent
if response_sent:
return
if message["type"] == "http.response.start":
status_code = message["status"]
if status_code == fastapi.status.HTTP_404_NOT_FOUND:
response = responses.FileResponse(self.static_dir / "index.html")
await response(scope, receive, send)
response_sent = True
else:
await send(message)
elif message["type"] == "http.response.body":
if not response_sent:
await send(message)
await self.app(scope, receive, send_wrapper) |
Beta Was this translation helpful? Give feedback.
Answered by
adriangb
Feb 5, 2025
Replies: 2 comments 2 replies
-
|
At a glance it looks good to me! My onbly doubt would be handling of |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
cyberksh
-
|
I would only have two notes:
|
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
At a glance it looks good to me! My onbly doubt would be handling of
if response_sent:. Are you sure you want to do nothing? Not callsend()? Raise an error?