app.py 5.4 KB

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