Fred808 commited on
Commit
010faf0
·
verified ·
1 Parent(s): 92e7857

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +86 -72
app/main.py CHANGED
@@ -1,72 +1,86 @@
1
- import os
2
- import sys
3
- from pathlib import Path
4
- from fastapi import FastAPI, HTTPException
5
- from fastapi.middleware.cors import CORSMiddleware
6
- from fastapi.responses import JSONResponse
7
- from .core.config import settings
8
- from .api.api_v1.api import api_router
9
- from .db.database import init_db
10
- import logging
11
- import asyncio
12
-
13
- # Set up Python path
14
- BASE_DIR = Path(__file__).resolve().parent.parent
15
- sys.path.append(str(BASE_DIR))
16
-
17
- # Configure logging
18
- logging.basicConfig(level=logging.INFO)
19
- logger = logging.getLogger(__name__)
20
-
21
- def create_app() -> FastAPI:
22
- app = FastAPI(
23
- title=settings.PROJECT_NAME,
24
- openapi_url=f"{settings.API_V1_STR}/openapi.json"
25
- )
26
-
27
- # Configure CORS
28
- app.add_middleware(
29
- CORSMiddleware,
30
- allow_origins=["*"],
31
- allow_credentials=True,
32
- allow_methods=["*"],
33
- allow_headers=["*"],
34
- )
35
-
36
- # Include API router
37
- app.include_router(api_router, prefix=settings.API_V1_STR)
38
-
39
- @app.exception_handler(HTTPException)
40
- async def http_exception_handler(request, exc):
41
- return JSONResponse(
42
- status_code=exc.status_code,
43
- content={"detail": exc.detail}
44
- )
45
-
46
- @app.get("/")
47
- async def root():
48
- return {"message": "POS Backend API", "version": "1.0.0"}
49
-
50
- @app.on_event("startup")
51
- async def startup_event():
52
- try:
53
- await init_db()
54
- logger.info("Database initialized successfully")
55
- except Exception as e:
56
- logger.error(f"Failed to initialize database: {e}")
57
- raise
58
-
59
- return app
60
-
61
- app = create_app()
62
-
63
- if __name__ == "__main__":
64
- import uvicorn
65
-
66
- uvicorn.run(
67
- "app.main:app",
68
- host="0.0.0.0",
69
- port=8000,
70
- reload=True,
71
- log_level="info"
72
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import asyncio
4
+ import platform
5
+ from pathlib import Path
6
+ from fastapi import FastAPI, HTTPException
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from fastapi.responses import JSONResponse
9
+ from .core.config import settings
10
+ from .api.v1.endpoints import auth, menu, orders, payments, reports
11
+ from .db.database import init_db
12
+ import logging
13
+
14
+ # Set up Python path
15
+ BASE_DIR = Path(__file__).resolve().parent.parent
16
+ sys.path.append(str(BASE_DIR))
17
+
18
+ # Configure Windows-specific event loop policy
19
+ if platform.system() == 'Windows':
20
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
21
+
22
+ # Configure detailed logging
23
+ logging.basicConfig(
24
+ level=logging.DEBUG,
25
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
26
+ stream=sys.stdout
27
+ )
28
+ logger = logging.getLogger(__name__)
29
+
30
+ def create_app() -> FastAPI:
31
+ app = FastAPI(
32
+ title=settings.PROJECT_NAME,
33
+ openapi_url=f"{settings.API_V1_STR}/openapi.json"
34
+ )
35
+
36
+ # Configure CORS
37
+ app.add_middleware(
38
+ CORSMiddleware,
39
+ allow_origins=["*"],
40
+ allow_credentials=True,
41
+ allow_methods=["*"],
42
+ allow_headers=["*"]
43
+ )
44
+
45
+ # Include API routers
46
+ app.include_router(auth.router, prefix=f"{settings.API_V1_STR}/auth", tags=["auth"])
47
+ app.include_router(menu.router, prefix=f"{settings.API_V1_STR}/menu", tags=["menu"])
48
+ app.include_router(orders.router, prefix=f"{settings.API_V1_STR}/orders", tags=["orders"])
49
+ app.include_router(payments.router, prefix=f"{settings.API_V1_STR}/payments", tags=["payments"])
50
+ app.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])
51
+
52
+ @app.exception_handler(HTTPException)
53
+ async def http_exception_handler(request, exc):
54
+ return JSONResponse(
55
+ status_code=exc.status_code,
56
+ content={"detail": exc.detail}
57
+ )
58
+
59
+ @app.get("/")
60
+ async def root():
61
+ return {"message": "POS Backend API", "version": "1.0.0"}
62
+
63
+ @app.on_event("startup")
64
+ async def startup_event():
65
+ try:
66
+ logger.info("Starting application initialization...")
67
+ await init_db()
68
+ logger.info("Database initialized successfully")
69
+ except Exception as e:
70
+ logger.error(f"Failed to initialize database: {str(e)}", exc_info=True)
71
+ raise
72
+
73
+ return app
74
+
75
+ app = create_app()
76
+
77
+ if __name__ == "__main__":
78
+ import uvicorn
79
+
80
+ uvicorn.run(
81
+ "app.main:app",
82
+ host="0.0.0.0",
83
+ port=8000,
84
+ reload=True,
85
+ log_level="info"
86
+ )