-
Notifications
You must be signed in to change notification settings - Fork 134
/
main.py
157 lines (121 loc) · 4.15 KB
/
main.py
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import uvicorn
from fastapi.staticfiles import StaticFiles
import uvicorn, os
from sqlalchemy.exc import IntegrityError
from fastapi import HTTPException, Request
from slowapi import Limiter
from slowapi.util import get_remote_address
from fastapi.templating import Jinja2Templates
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from fastapi import FastAPI, status
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.middleware.sessions import SessionMiddleware # required by google oauth
from api.utils.json_response import JsonResponseDict
from api.utils.logger import logger
from api.v1.routes import api_version_one
from api.utils.settings import settings
from scripts.populate_db import populate_roles_and_permissions
@asynccontextmanager
async def lifespan(app: FastAPI):
'''Lifespan function'''
yield
app = FastAPI(
lifespan=lifespan,
title="HNG Boilerplate",
description="A boilerplate for creating an API using FastAPI and SQLAlchemy",
version="1.0.0",
)
# Initialize the rate limiter
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
# Set up email templates and css static files
email_templates = Jinja2Templates(directory='api/core/dependencies/email/templates')
# MEDIA_DIR = os.path.expanduser('~/.media')
MEDIA_DIR = './media'
if not os.path.exists(MEDIA_DIR):
os.makedirs(MEDIA_DIR)
# Load up media static files
app.mount('/media', StaticFiles(directory=MEDIA_DIR), name='media')
origins = [
"http://localhost:3000",
"http://localhost:3001",
'https://anchor-python.teams.hng.tech',
]
app.add_middleware(SessionMiddleware, secret_key=settings.SECRET_KEY)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_version_one)
@app.get("/", tags=["Home"])
async def get_root(request: Request) -> dict:
return JsonResponseDict(
message="Welcome to API", status_code=status.HTTP_200_OK, data={"URL": ""}
)
@app.get("/probe", tags=["Home"])
async def probe():
return {"message": "I am the Python FastAPI API responding"}
# REGISTER EXCEPTION HANDLERS
@app.exception_handler(HTTPException)
async def http_exception(request: Request, exc: HTTPException):
"""HTTP exception handler"""
return JSONResponse(
status_code=exc.status_code,
content={
"status": False,
"status_code": exc.status_code,
"message": exc.detail,
},
)
@app.exception_handler(RequestValidationError)
async def validation_exception(request: Request, exc: RequestValidationError):
"""Validation exception handler"""
errors = [
{"loc": error["loc"], "msg": error["msg"], "type": error["type"]}
for error in exc.errors()
]
return JSONResponse(
status_code=422,
content={
"status": False,
"status_code": 422,
"message": "Invalid input",
"errors": errors,
},
)
@app.exception_handler(IntegrityError)
async def exception(request: Request, exc: IntegrityError):
"""Integrity error exception handlers"""
logger.exception(f"Exception occured; {exc}")
return JSONResponse(
status_code=400,
content={
"status": False,
"status_code": 400,
"message": f"An unexpected error occurred: {exc}",
},
)
@app.exception_handler(Exception)
async def exception(request: Request, exc: Exception):
"""Other exception handlers"""
logger.exception(f"Exception occured; {exc}")
return JSONResponse(
status_code=500,
content={
"status": False,
"status_code": 500,
"message": f"An unexpected error occurred: {exc}",
},
)
STATIC_DIR = "static/profile_images"
os.makedirs(STATIC_DIR, exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")
if __name__ == "__main__":
uvicorn.run("main:app", port=7001, reload=True)