File size: 2,282 Bytes
9d4bd7c
 
 
 
 
 
 
 
 
 
 
b06927a
9c765c3
9d4bd7c
9c765c3
9d4bd7c
 
 
 
 
 
 
 
9c765c3
9d4bd7c
 
9c765c3
9d4bd7c
 
 
 
 
9c765c3
 
9d4bd7c
 
9c765c3
0cabf6c
e558c69
 
 
 
 
 
 
9d4bd7c
 
 
 
 
 
 
 
b06927a
9d4bd7c
9c765c3
9d4bd7c
 
 
 
 
 
9c765c3
9d4bd7c
 
 
 
 
9c765c3
9d4bd7c
 
 
9c765c3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError, HTTPException
from starlette.status import HTTP_400_BAD_REQUEST
from App.routers.stocks.routes import router as stocks_router
from App.routers.utt.routes import router as utt_router
from App.routers.bonds.routes import router as bonds_router
from App.routers.tasks.routes import router as tasks_router
from App.routers.users.routes import router as users_router
from App.routers.portfolio.routes import router as portfolio_router
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
from App.schemas import ResponseModel, AppException

from db import init_db, close_db, clear_db

app = FastAPI(title="Uwekezaji API", description="Stock Market Data API")


@app.exception_handler(AppException)
async def custom_http_exception_handler(request: Request, exc: AppException):
    return JSONResponse(
        status_code=exc.status_code,
        content=ResponseModel(success=False, message=exc.detail, data=exc.data).dict(),
    )


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=HTTP_400_BAD_REQUEST,
        content=ResponseModel(
            success=False, message="Validation error", data={"errors": exc.errors()}
        ).dict(),
    )


# # Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(stocks_router)
app.include_router(utt_router)
app.include_router(bonds_router)
app.include_router(tasks_router)
app.include_router(users_router)
app.include_router(portfolio_router)
app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")


# Database initialization and cleanup
@app.on_event("startup")
async def startup_event():
    # Clear and reinitialize database on startup
    await init_db()


@app.on_event("shutdown")
async def shutdown_event():
    # await clear_db()
    await close_db()


# Root endpoint
@app.get("/")
async def root():
    return {"message": "Welcome to Uwekezaji API"}