app.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. from math import log
  2. from fastapi import FastAPI
  3. from fastapi.middleware.cors import CORSMiddleware
  4. from starlette.middleware.sessions import SessionMiddleware
  5. from config.settings import DEVELOPMENT, SECRET_KEY
  6. from models import user
  7. from routes import sales
  8. from services.email_service import initialize_email_sender
  9. from middleware.no_cache import NoCacheMiddleware
  10. from logging import getLogger
  11. logger = getLogger(__name__)
  12. def create_app() -> FastAPI:
  13. """Create and configure FastAPI application"""
  14. logger.info("Creating FastAPI application")
  15. try:
  16. if DEVELOPMENT:
  17. logger.info("Creating FastAPI app in development mode")
  18. app = FastAPI(
  19. title="Web Pedidos Klein - FastAPI Backend",
  20. description="Backend for the Web Pedidos Klein application using FastAPI"
  21. )
  22. else:
  23. logger.info("Creating FastAPI app in production mode")
  24. app = FastAPI(
  25. title="Web Pedidos Klein - FastAPI Backend",
  26. description="Backend for the Web Pedidos Klein application using FastAPI",
  27. version="1.0.0",
  28. docs_url=None,
  29. redoc_url=None
  30. )
  31. # Initialize email sender
  32. logger.info("Initializing email sender")
  33. initialize_email_sender()
  34. logger.info("Email sender initialized")
  35. # Add CORS middleware
  36. logger.info("Adding CORS middleware")
  37. app.add_middleware(
  38. CORSMiddleware,
  39. allow_origins=["https://admin.kleinexpress.store"],
  40. allow_credentials=True,
  41. allow_methods=["*"],
  42. allow_headers=["*"],
  43. )
  44. # Add SessionMiddleware
  45. logger.info("Adding session middleware")
  46. app.add_middleware(
  47. SessionMiddleware,
  48. secret_key=SECRET_KEY,
  49. max_age=60 * 60 # max_age in seconds for Starlette
  50. )
  51. # Add NoCacheMiddleware
  52. logger.info("Adding no-cache middleware")
  53. app.add_middleware(NoCacheMiddleware)
  54. logger.info("FastAPI application created successfully")
  55. return app
  56. except Exception as e:
  57. error_msg = f"Error creating FastAPI application: {e}"
  58. logger.error(error_msg)
  59. raise
  60. def setup_routes(app: FastAPI):
  61. """Setup all application routes"""
  62. logger.info("Setting up application routes")
  63. try:
  64. from routes import chat, users, products, orders, static
  65. from fastapi import Depends
  66. from auth.security import get_current_user
  67. # Chat routes
  68. logger.info("Setting up chat routes")
  69. app.include_router(
  70. chat.chat_router,
  71. prefix="/api/chat",
  72. tags=["Chat"],
  73. dependencies=[Depends(get_current_user)]
  74. )
  75. # User routes
  76. logger.info("Setting up user routes")
  77. app.include_router(users.user_router, prefix="/api/users", tags=["Users"])
  78. # Product routes
  79. logger.info("Setting up product routes")
  80. app.include_router(
  81. products.product_router,
  82. prefix="/api/products",
  83. tags=["Products"],
  84. dependencies=[Depends(get_current_user)]
  85. )
  86. # Order routes
  87. logger.info("Setting up order routes")
  88. app.include_router(
  89. orders.order_router,
  90. prefix="/api/orders",
  91. tags=["Orders"],
  92. dependencies=[Depends(get_current_user)]
  93. )
  94. # Sales routes
  95. logger.info("Setting up sales routes")
  96. app.include_router(
  97. sales.sales_router,
  98. prefix="/api/sales",
  99. tags=["Sales"],
  100. dependencies=[Depends(get_current_user)]
  101. )
  102. # Verification routes
  103. logger.info("Setting up verification routes")
  104. app.include_router(users.verify_router, prefix="/verify", tags=["Verification"])
  105. app.include_router(users.recovery_pin_router, prefix="/recovery", tags=["Recovery PIN"])
  106. # Static routes
  107. logger.info("Setting up static routes")
  108. from fastapi.responses import HTMLResponse
  109. app.add_api_route("/", static.serve_app_html, methods=["GET"],
  110. response_class=HTMLResponse, include_in_schema=False)
  111. app.add_api_route("/register", static.serve_register_html, methods=["GET"],
  112. response_class=HTMLResponse, include_in_schema=False)
  113. app.add_api_route("/images/{image_path:path}", static.serve_image, methods=["GET"],
  114. response_class=HTMLResponse, include_in_schema=False)
  115. # Mount static files
  116. logger.info("Mounting static file directories")
  117. static.mount_main_static_files(app)
  118. static.mount_register_static_files(app)
  119. logger.info("Application routes setup completed successfully")
  120. except Exception as e:
  121. error_msg = f"Error setting up application routes: - {e}"
  122. logger.error(error_msg)
  123. raise