-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
71 lines (57 loc) · 1.95 KB
/
main.py
File metadata and controls
71 lines (57 loc) · 1.95 KB
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
import time
import redis.asyncio as redis
from fastapi import FastAPI, Depends, HTTPException, status, Request
from fastapi_limiter import FastAPILimiter
from sqlalchemy import text
from sqlalchemy.orm import Session
from fastapi.middleware.cors import CORSMiddleware
from src.config.config import settings
from src.database.db import get_db
from src.routes import contacts, auth, users
app = FastAPI()
origins = [
"http://localhost:3000"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(auth.router, prefix='/api')
app.include_router(contacts.router, prefix="/api")
app.include_router(users.router, prefix='/api')
@app.on_event("startup")
async def startup():
r = await redis.Redis(host=settings.redis_host, port=settings.redis_port, db=0, encoding="utf-8",
decode_responses=True)
await FastAPILimiter.init(r)
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["My-Process-Time"] = str(process_time)
return response
@app.get("/", name="Project")
def read_root():
return {"message": "Hello, world!"}
@app.get("/api/healthchecker")
def healthchecker(db: Session = Depends(get_db)):
try:
# Make request
result = db.execute(text("SELECT 1")).fetchone()
print(result)
if result is None:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Database is not configured correctly",
)
return {"message": "Welcome to FastAPI!"}
except Exception as e:
print(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error connecting to the database",
)