middleware.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from urllib.parse import urlparse
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from starlette.middleware.base import BaseHTTPMiddleware
  4. from starlette.types import ASGIApp
  5. class LocalhostCORSMiddleware(CORSMiddleware):
  6. """
  7. Custom CORS middleware that allows any request from localhost/127.0.0.1 domains,
  8. while using standard CORS rules for other origins.
  9. """
  10. def __init__(self, app: ASGIApp, **kwargs) -> None:
  11. super().__init__(app, **kwargs)
  12. def is_allowed_origin(self, origin: str) -> bool:
  13. if origin:
  14. parsed = urlparse(origin)
  15. hostname = parsed.hostname or ''
  16. # Allow any localhost/127.0.0.1 origin regardless of port
  17. if hostname in ['localhost', '127.0.0.1']:
  18. return True
  19. # For missing origin or other origins, use the parent class's logic
  20. return super().is_allowed_origin(origin)
  21. class NoCacheMiddleware(BaseHTTPMiddleware):
  22. """
  23. Middleware to disable caching for all routes by adding appropriate headers
  24. """
  25. async def dispatch(self, request, call_next):
  26. response = await call_next(request)
  27. if not request.url.path.startswith('/assets'):
  28. response.headers['Cache-Control'] = (
  29. 'no-cache, no-store, must-revalidate, max-age=0'
  30. )
  31. response.headers['Pragma'] = 'no-cache'
  32. response.headers['Expires'] = '0'
  33. return response