Spaces:
Paused
Paused
Update app/main.py
Browse files- app/main.py +107 -107
app/main.py
CHANGED
|
@@ -1,108 +1,108 @@
|
|
| 1 |
-
from fastapi import FastAPI, Request, WebSocket
|
| 2 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
from .core.config import settings
|
| 4 |
-
from .db.database import engine, Base
|
| 5 |
-
from .api import auth, products, orders, users, analytics, files, notifications, calendar, scheduler, maintenance
|
| 6 |
-
from .utils.rate_limiter import rate_limiter
|
| 7 |
-
from .utils.logger import log_api_request
|
| 8 |
-
from .utils.tasks import run_periodic_tasks
|
| 9 |
-
import time
|
| 10 |
-
import logging
|
| 11 |
-
import asyncio
|
| 12 |
-
from typing import List
|
| 13 |
-
|
| 14 |
-
# Configure logging
|
| 15 |
-
logging.basicConfig(level=logging.INFO)
|
| 16 |
-
logger = logging.getLogger(__name__)
|
| 17 |
-
|
| 18 |
-
app = FastAPI(title=settings.PROJECT_NAME, version=settings.VERSION)
|
| 19 |
-
|
| 20 |
-
# Store active WebSocket connections and background tasks
|
| 21 |
-
active_connections: List[WebSocket] = []
|
| 22 |
-
background_tasks = set()
|
| 23 |
-
|
| 24 |
-
# Configure CORS
|
| 25 |
-
app.add_middleware(
|
| 26 |
-
CORSMiddleware,
|
| 27 |
-
allow_origins=["*"], # Configure appropriately for production
|
| 28 |
-
allow_credentials=True,
|
| 29 |
-
allow_methods=["*"],
|
| 30 |
-
allow_headers=["*"],
|
| 31 |
-
)
|
| 32 |
-
|
| 33 |
-
# WebSocket connection manager
|
| 34 |
-
@app.websocket("/ws")
|
| 35 |
-
async def websocket_endpoint(websocket: WebSocket):
|
| 36 |
-
await websocket.accept()
|
| 37 |
-
active_connections.append(websocket)
|
| 38 |
-
try:
|
| 39 |
-
while True:
|
| 40 |
-
data = await websocket.receive_text()
|
| 41 |
-
except:
|
| 42 |
-
active_connections.remove(websocket)
|
| 43 |
-
|
| 44 |
-
# Notification broadcaster
|
| 45 |
-
async def broadcast_notification(message: dict):
|
| 46 |
-
for connection in active_connections:
|
| 47 |
-
try:
|
| 48 |
-
await connection.send_json(message)
|
| 49 |
-
except:
|
| 50 |
-
active_connections.remove(connection)
|
| 51 |
-
|
| 52 |
-
# Request logging and rate limiting middleware
|
| 53 |
-
@app.middleware("http")
|
| 54 |
-
async def middleware(request: Request, call_next):
|
| 55 |
-
await rate_limiter.check_rate_limit(request)
|
| 56 |
-
start_time = time.time()
|
| 57 |
-
response = await call_next(request)
|
| 58 |
-
end_time = time.time()
|
| 59 |
-
duration = end_time - start_time
|
| 60 |
-
log_api_request(
|
| 61 |
-
method=request.method,
|
| 62 |
-
path=request.url.path,
|
| 63 |
-
status_code=response.status_code,
|
| 64 |
-
duration=duration
|
| 65 |
-
)
|
| 66 |
-
return response
|
| 67 |
-
|
| 68 |
-
# Application startup and shutdown events
|
| 69 |
-
@app.on_event("startup")
|
| 70 |
-
async def startup_event():
|
| 71 |
-
# Create all database tables
|
| 72 |
-
async with engine.begin() as conn:
|
| 73 |
-
await conn.run_sync(Base.metadata.create_all)
|
| 74 |
-
|
| 75 |
-
# Start background tasks
|
| 76 |
-
task = asyncio.create_task(run_periodic_tasks())
|
| 77 |
-
background_tasks.add(task)
|
| 78 |
-
task.add_done_callback(background_tasks.discard)
|
| 79 |
-
|
| 80 |
-
@app.on_event("shutdown")
|
| 81 |
-
async def shutdown_event():
|
| 82 |
-
# Cancel background tasks
|
| 83 |
-
for task in background_tasks:
|
| 84 |
-
task.cancel()
|
| 85 |
-
|
| 86 |
-
# Close WebSocket connections
|
| 87 |
-
for connection in active_connections:
|
| 88 |
-
await connection.close()
|
| 89 |
-
|
| 90 |
-
# Include routers
|
| 91 |
-
app.include_router(auth.router, prefix=f"{settings.API_V1_STR}/auth", tags=["auth"])
|
| 92 |
-
app.include_router(users.router, prefix=f"{settings.API_V1_STR}/users", tags=["users"])
|
| 93 |
-
app.include_router(products.router, prefix=f"{settings.API_V1_STR}/products", tags=["products"])
|
| 94 |
-
app.include_router(orders.router, prefix=f"{settings.API_V1_STR}/orders", tags=["orders"])
|
| 95 |
-
app.include_router(analytics.router, prefix=f"{settings.API_V1_STR}/analytics", tags=["analytics"])
|
| 96 |
-
app.include_router(files.router, prefix=f"{settings.API_V1_STR}/files", tags=["files"])
|
| 97 |
-
app.include_router(notifications.router, prefix=f"{settings.API_V1_STR}/notifications", tags=["notifications"])
|
| 98 |
-
app.include_router(calendar.router, prefix=f"{settings.API_V1_STR}/calendar", tags=["calendar"])
|
| 99 |
-
app.include_router(scheduler.router, prefix=f"{settings.API_V1_STR}/scheduler", tags=["scheduler"])
|
| 100 |
-
app.include_router(maintenance.router, prefix=f"{settings.API_V1_STR}/maintenance", tags=["maintenance"])
|
| 101 |
-
|
| 102 |
-
@app.get("/")
|
| 103 |
-
async def root():
|
| 104 |
-
return {
|
| 105 |
-
"message": f"Welcome to {settings.PROJECT_NAME} v{settings.VERSION}",
|
| 106 |
-
"docs_url": "/docs",
|
| 107 |
-
"openapi_url": "/openapi.json"
|
| 108 |
}
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, WebSocket
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from .core.config import settings
|
| 4 |
+
from .db.database import async_engine as engine, Base
|
| 5 |
+
from .api import auth, products, orders, users, analytics, files, notifications, calendar, scheduler, maintenance
|
| 6 |
+
from .utils.rate_limiter import rate_limiter
|
| 7 |
+
from .utils.logger import log_api_request
|
| 8 |
+
from .utils.tasks import run_periodic_tasks
|
| 9 |
+
import time
|
| 10 |
+
import logging
|
| 11 |
+
import asyncio
|
| 12 |
+
from typing import List
|
| 13 |
+
|
| 14 |
+
# Configure logging
|
| 15 |
+
logging.basicConfig(level=logging.INFO)
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
app = FastAPI(title=settings.PROJECT_NAME, version=settings.VERSION)
|
| 19 |
+
|
| 20 |
+
# Store active WebSocket connections and background tasks
|
| 21 |
+
active_connections: List[WebSocket] = []
|
| 22 |
+
background_tasks = set()
|
| 23 |
+
|
| 24 |
+
# Configure CORS
|
| 25 |
+
app.add_middleware(
|
| 26 |
+
CORSMiddleware,
|
| 27 |
+
allow_origins=["*"], # Configure appropriately for production
|
| 28 |
+
allow_credentials=True,
|
| 29 |
+
allow_methods=["*"],
|
| 30 |
+
allow_headers=["*"],
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# WebSocket connection manager
|
| 34 |
+
@app.websocket("/ws")
|
| 35 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 36 |
+
await websocket.accept()
|
| 37 |
+
active_connections.append(websocket)
|
| 38 |
+
try:
|
| 39 |
+
while True:
|
| 40 |
+
data = await websocket.receive_text()
|
| 41 |
+
except:
|
| 42 |
+
active_connections.remove(websocket)
|
| 43 |
+
|
| 44 |
+
# Notification broadcaster
|
| 45 |
+
async def broadcast_notification(message: dict):
|
| 46 |
+
for connection in active_connections:
|
| 47 |
+
try:
|
| 48 |
+
await connection.send_json(message)
|
| 49 |
+
except:
|
| 50 |
+
active_connections.remove(connection)
|
| 51 |
+
|
| 52 |
+
# Request logging and rate limiting middleware
|
| 53 |
+
@app.middleware("http")
|
| 54 |
+
async def middleware(request: Request, call_next):
|
| 55 |
+
await rate_limiter.check_rate_limit(request)
|
| 56 |
+
start_time = time.time()
|
| 57 |
+
response = await call_next(request)
|
| 58 |
+
end_time = time.time()
|
| 59 |
+
duration = end_time - start_time
|
| 60 |
+
log_api_request(
|
| 61 |
+
method=request.method,
|
| 62 |
+
path=request.url.path,
|
| 63 |
+
status_code=response.status_code,
|
| 64 |
+
duration=duration
|
| 65 |
+
)
|
| 66 |
+
return response
|
| 67 |
+
|
| 68 |
+
# Application startup and shutdown events
|
| 69 |
+
@app.on_event("startup")
|
| 70 |
+
async def startup_event():
|
| 71 |
+
# Create all database tables
|
| 72 |
+
async with engine.begin() as conn:
|
| 73 |
+
await conn.run_sync(Base.metadata.create_all)
|
| 74 |
+
|
| 75 |
+
# Start background tasks
|
| 76 |
+
task = asyncio.create_task(run_periodic_tasks())
|
| 77 |
+
background_tasks.add(task)
|
| 78 |
+
task.add_done_callback(background_tasks.discard)
|
| 79 |
+
|
| 80 |
+
@app.on_event("shutdown")
|
| 81 |
+
async def shutdown_event():
|
| 82 |
+
# Cancel background tasks
|
| 83 |
+
for task in background_tasks:
|
| 84 |
+
task.cancel()
|
| 85 |
+
|
| 86 |
+
# Close WebSocket connections
|
| 87 |
+
for connection in active_connections:
|
| 88 |
+
await connection.close()
|
| 89 |
+
|
| 90 |
+
# Include routers
|
| 91 |
+
app.include_router(auth.router, prefix=f"{settings.API_V1_STR}/auth", tags=["auth"])
|
| 92 |
+
app.include_router(users.router, prefix=f"{settings.API_V1_STR}/users", tags=["users"])
|
| 93 |
+
app.include_router(products.router, prefix=f"{settings.API_V1_STR}/products", tags=["products"])
|
| 94 |
+
app.include_router(orders.router, prefix=f"{settings.API_V1_STR}/orders", tags=["orders"])
|
| 95 |
+
app.include_router(analytics.router, prefix=f"{settings.API_V1_STR}/analytics", tags=["analytics"])
|
| 96 |
+
app.include_router(files.router, prefix=f"{settings.API_V1_STR}/files", tags=["files"])
|
| 97 |
+
app.include_router(notifications.router, prefix=f"{settings.API_V1_STR}/notifications", tags=["notifications"])
|
| 98 |
+
app.include_router(calendar.router, prefix=f"{settings.API_V1_STR}/calendar", tags=["calendar"])
|
| 99 |
+
app.include_router(scheduler.router, prefix=f"{settings.API_V1_STR}/scheduler", tags=["scheduler"])
|
| 100 |
+
app.include_router(maintenance.router, prefix=f"{settings.API_V1_STR}/maintenance", tags=["maintenance"])
|
| 101 |
+
|
| 102 |
+
@app.get("/")
|
| 103 |
+
async def root():
|
| 104 |
+
return {
|
| 105 |
+
"message": f"Welcome to {settings.PROJECT_NAME} v{settings.VERSION}",
|
| 106 |
+
"docs_url": "/docs",
|
| 107 |
+
"openapi_url": "/openapi.json"
|
| 108 |
}
|