app_module_for_backend.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. """Shims the real reflex app module for running backend server (uvicorn or gunicorn).
  2. Only the app attribute is explicitly exposed.
  3. """
  4. from concurrent.futures import ThreadPoolExecutor
  5. from reflex import constants
  6. from reflex.utils import telemetry
  7. from reflex.utils.exec import is_prod_mode
  8. from reflex.utils.prerequisites import get_app
  9. if "app" != constants.CompileVars.APP:
  10. raise AssertionError("unexpected variable name for 'app'")
  11. telemetry.send("compile")
  12. app_module = get_app(reload=False)
  13. app = getattr(app_module, constants.CompileVars.APP)
  14. # For py3.8 and py3.9 compatibility when redis is used, we MUST add any decorator pages
  15. # before compiling the app in a thread to avoid event loop error (REF-2172).
  16. app._apply_decorated_pages()
  17. compile_future = ThreadPoolExecutor(max_workers=1).submit(app._compile)
  18. compile_future.add_done_callback(
  19. # Force background compile errors to print eagerly
  20. lambda f: f.result()
  21. )
  22. # Wait for the compile to finish in prod mode to ensure all optional endpoints are mounted.
  23. if is_prod_mode():
  24. compile_future.result()
  25. # ensure only "app" is exposed.
  26. del app_module
  27. del compile_future
  28. del get_app
  29. del is_prod_mode
  30. del telemetry
  31. del constants
  32. del ThreadPoolExecutor