-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
68 lines (53 loc) · 1.97 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
import time
from typing import Optional
import uvicorn
from fastapi import FastAPI, Body, Request, Depends
from fastapi.responses import JSONResponse
from app.routes import router as api_router
from config import DEBUG
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from app.user.auth import validate_token, CustomHTTPException
app = FastAPI()
origins = [
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.exception_handler(CustomHTTPException)
async def custom_exception_handler(request, exc: CustomHTTPException):
return JSONResponse(status_code=exc.status_code, content=exc.detail)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
class CustomErrorResponse(BaseModel):
success: bool = False
error: str
code: int
error_description: Optional[list]
errors = exc.errors()
error_messages = []
for error in errors:
print("error",error)
if len(error["loc"])>1:
field = error["loc"][1]
else:
field = error["loc"][0]
message = error["msg"]
error_messages.append(f"Field '{field}': {message}")
error_response = CustomErrorResponse(error="Validation error", code=422, error_description=error_messages)
return JSONResponse(content=error_response.dict(), status_code=422)
app.include_router(api_router)
@app.get('/')
def base(request: Request):
print("hey")
return "OK"
if __name__ == "__main__" and DEBUG:
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True, log_level="debug", ssl_keyfile="ssl_private_key.pem", ssl_certfile="ssl_certificate.pem",
workers=1)
# uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True, log_level="debug", workers=1)