app.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. from fastapi import FastAPI
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from starlette.middleware.sessions import SessionMiddleware
  4. from config.settings import DEVELOPMENT, SECRET_KEY
  5. from routes import sales
  6. from services.email_service import initialize_email_sender
  7. from services.logging_service import structured_logger, LogLevel
  8. from logging import getLogger
  9. logger = getLogger(__name__)
  10. def create_app() -> FastAPI:
  11. """Create and configure FastAPI application"""
  12. logger.info("Creating FastAPI application")
  13. try:
  14. if DEVELOPMENT:
  15. logger.info("Creating FastAPI app in development mode")
  16. app = FastAPI(
  17. title="Web Pedidos Klein - FastAPI Backend",
  18. description="Backend for the Web Pedidos Klein application using FastAPI"
  19. )
  20. else:
  21. logger.info("Creating FastAPI app in production mode")
  22. app = FastAPI(
  23. title="Web Pedidos Klein - FastAPI Backend",
  24. description="Backend for the Web Pedidos Klein application using FastAPI",
  25. version="1.0.0",
  26. docs_url=None,
  27. redoc_url=None
  28. )
  29. structured_logger.log_system_event(
  30. "FastAPI application created",
  31. LogLevel.INFO,
  32. {
  33. "development_mode": DEVELOPMENT,
  34. "docs_enabled": DEVELOPMENT,
  35. "title": "Web Pedidos Klein - FastAPI Backend"
  36. }
  37. )
  38. # Initialize email sender
  39. logger.info("Initializing email sender")
  40. initialize_email_sender()
  41. structured_logger.log_email_event(
  42. "Email sender initialized",
  43. LogLevel.INFO
  44. )
  45. # Add CORS middleware
  46. logger.info("Adding CORS middleware")
  47. app.add_middleware(
  48. CORSMiddleware,
  49. allow_origins=["https://admin.kleinexpress.store"],
  50. allow_credentials=True,
  51. allow_methods=["*"],
  52. allow_headers=["*"],
  53. )
  54. structured_logger.log_system_event(
  55. "CORS middleware configured",
  56. LogLevel.INFO,
  57. {
  58. "allowed_origins": ["https://admin.kleinexpress.store"],
  59. "allow_credentials": True
  60. }
  61. )
  62. # Add SessionMiddleware
  63. logger.info("Adding session middleware")
  64. app.add_middleware(
  65. SessionMiddleware,
  66. secret_key=SECRET_KEY,
  67. max_age=60 * 60 # max_age in seconds for Starlette
  68. )
  69. structured_logger.log_system_event(
  70. "Session middleware configured",
  71. LogLevel.INFO,
  72. {"max_age_seconds": 3600}
  73. )
  74. logger.info("FastAPI application created successfully")
  75. return app
  76. except Exception as e:
  77. error_msg = f"Error creating FastAPI application: {e}"
  78. logger.error(error_msg)
  79. structured_logger.log_system_event(
  80. "FastAPI application creation failed",
  81. LogLevel.ERROR,
  82. {
  83. "error": str(e),
  84. "error_type": type(e).__name__
  85. }
  86. )
  87. raise
  88. def setup_routes(app: FastAPI):
  89. """Setup all application routes"""
  90. logger.info("Setting up application routes")
  91. try:
  92. from routes import chat, users, products, orders, static
  93. from fastapi import Depends
  94. from auth.security import get_current_user
  95. # Chat routes
  96. logger.info("Setting up chat routes")
  97. app.include_router(
  98. chat.chat_router,
  99. prefix="/api/chat",
  100. tags=["Chat"],
  101. dependencies=[Depends(get_current_user)]
  102. )
  103. # User routes
  104. logger.info("Setting up user routes")
  105. app.include_router(users.user_router, prefix="/api/users", tags=["Users"])
  106. # Product routes
  107. logger.info("Setting up product routes")
  108. app.include_router(
  109. products.product_router,
  110. prefix="/api/products",
  111. tags=["Products"],
  112. dependencies=[Depends(get_current_user)]
  113. )
  114. # Order routes
  115. logger.info("Setting up order routes")
  116. app.include_router(
  117. orders.order_router,
  118. prefix="/api/orders",
  119. tags=["Orders"],
  120. dependencies=[Depends(get_current_user)]
  121. )
  122. # Sales routes
  123. logger.info("Setting up sales routes")
  124. app.include_router(
  125. sales.sales_router,
  126. prefix="/api/sales",
  127. tags=["Sales"],
  128. dependencies=[Depends(get_current_user)]
  129. )
  130. # Verification routes
  131. logger.info("Setting up verification routes")
  132. app.include_router(users.verify_router, prefix="/verify", tags=["Verification"])
  133. # Static routes
  134. logger.info("Setting up static routes")
  135. from fastapi.responses import HTMLResponse
  136. app.add_api_route("/", static.serve_app_html, methods=["GET"],
  137. response_class=HTMLResponse, include_in_schema=False)
  138. app.add_api_route("/register", static.serve_register_html, methods=["GET"],
  139. response_class=HTMLResponse, include_in_schema=False)
  140. app.add_api_route("/images/{image_path:path}", static.serve_image, methods=["GET"],
  141. response_class=HTMLResponse, include_in_schema=False)
  142. # Mount static files
  143. logger.info("Mounting static file directories")
  144. static.mount_main_static_files(app)
  145. static.mount_register_static_files(app)
  146. structured_logger.log_system_event(
  147. "All application routes configured successfully",
  148. LogLevel.INFO,
  149. {
  150. "route_groups": [
  151. "chat", "users", "products", "orders",
  152. "sales", "verification", "static"
  153. ]
  154. }
  155. )
  156. logger.info("Application routes setup completed successfully")
  157. except Exception as e:
  158. error_msg = f"Error setting up application routes: {e}"
  159. logger.error(error_msg)
  160. structured_logger.log_system_event(
  161. "Route setup failed",
  162. LogLevel.ERROR,
  163. {
  164. "error": str(e),
  165. "error_type": type(e).__name__
  166. }
  167. )
  168. raise