Extract HTML5 response helpers
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
HTML5_SECURITY_HEADERS = {"X-Content-Type-Options": "nosniff"}
|
||||
|
||||
|
||||
class Html5StaticFiles(StaticFiles):
|
||||
def file_response(self, *args, **kwargs):
|
||||
response = super().file_response(*args, **kwargs)
|
||||
response.headers.setdefault("Cache-Control", "public, max-age=86400")
|
||||
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
||||
return response
|
||||
|
||||
|
||||
def html5_sse_headers() -> dict[str, str]:
|
||||
return {
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
**HTML5_SECURITY_HEADERS,
|
||||
}
|
||||
|
||||
|
||||
def html5_response(fragment: str) -> Response:
|
||||
return Response(
|
||||
fragment,
|
||||
media_type="text/html; charset=utf-8",
|
||||
headers={"Cache-Control": "no-cache, no-transform", **HTML5_SECURITY_HEADERS},
|
||||
)
|
||||
|
||||
|
||||
def html5_sse_response(content: Any) -> StreamingResponse:
|
||||
return StreamingResponse(
|
||||
content,
|
||||
media_type="text/event-stream",
|
||||
headers=html5_sse_headers(),
|
||||
)
|
||||
Reference in New Issue
Block a user