static.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. from fastapi import HTTPException
  3. from fastapi.responses import HTMLResponse, FileResponse
  4. from fastapi.staticfiles import StaticFiles
  5. from starlette.responses import Response
  6. from starlette.types import Scope, Receive, Send
  7. class NoCacheStaticFiles(StaticFiles):
  8. """StaticFiles que agrega headers para evitar cache"""
  9. async def get_response(self, path: str, scope: Scope) -> Response:
  10. """Override para agregar headers de no-cache"""
  11. response = await super().get_response(path, scope)
  12. # Agregar headers para evitar cache
  13. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0"
  14. response.headers["Pragma"] = "no-cache"
  15. response.headers["Expires"] = "0"
  16. return response
  17. async def serve_app_html():
  18. """Serve the main HTML file"""
  19. index_path = os.path.join("public","main", "index.html")
  20. if not os.path.exists(index_path):
  21. raise HTTPException(status_code=404, detail="public/index.html not found.")
  22. # Headers para evitar cache
  23. headers = {
  24. "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0",
  25. "Pragma": "no-cache",
  26. "Expires": "0"
  27. }
  28. return FileResponse(index_path, headers=headers)
  29. async def serve_register_html():
  30. """Serve the register HTML file"""
  31. register_path = os.path.join("public", "register", "index.html")
  32. if not os.path.exists(register_path):
  33. raise HTTPException(status_code=404, detail="public/register/index.html not found.")
  34. # Headers para evitar cache
  35. headers = {
  36. "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0",
  37. "Pragma": "no-cache",
  38. "Expires": "0"
  39. }
  40. return FileResponse(register_path, headers=headers)
  41. def mount_register_static_files(app):
  42. """Mount static files for the register page"""
  43. app.mount("/register/", NoCacheStaticFiles(directory="public/register", html=False), name="register_static")
  44. def mount_main_static_files(app):
  45. """Mount static files"""
  46. app.mount("/express/", NoCacheStaticFiles(directory="public/main", html=False), name="public_root_assets")
  47. def serve_image(image_path: str):
  48. """Serve images from the public/images directory"""
  49. image_full_path = os.path.join("public", "images", image_path)
  50. if not os.path.exists(image_full_path):
  51. raise HTTPException(status_code=404, detail=f"Image '{image_path}' not found.")
  52. # Headers para evitar cache en imágenes también
  53. headers = {
  54. "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0",
  55. "Pragma": "no-cache",
  56. "Expires": "0"
  57. }
  58. return FileResponse(image_full_path, headers=headers)