-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
66 lines (48 loc) · 2.04 KB
/
server.py
File metadata and controls
66 lines (48 loc) · 2.04 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
import os
from dotenv import load_dotenv
from fastapi import FastAPI, status
from fastapi.exception_handlers import request_validation_exception_handler
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from routes import v1
load_dotenv()
app = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
is_missing_app_id = False
is_missing_user_id = False
for error in exc.errors():
if error["type"] == "missing" and "aloy-app-id" in error["loc"]:
is_missing_app_id = True
elif error["type"] == "missing" and "aloy-user-id" in error["loc"]:
is_missing_user_id = True
if is_missing_app_id:
return JSONResponse(content={"error": {"code": "MISSING_APP_ID"}}, status_code=status.HTTP_400_BAD_REQUEST)
elif is_missing_user_id:
return JSONResponse(content={"error": {"code": "MISSING_USER_ID"}}, status_code=status.HTTP_400_BAD_REQUEST)
m = {}
for error in exc.errors():
loc = error["loc"]
key = loc[0 if len(loc) == 1 else 1] # When validating manually, the key will be the first item
match error["type"]:
case "missing":
m[key] = "REQUIRED"
case "value_error":
m[key] = str(error["ctx"]["error"])
if len(m) > 0:
return JSONResponse(content={"error": m}, status_code=status.HTTP_400_BAD_REQUEST)
return await request_validation_exception_handler(request, exc)
app.add_middleware(
CORSMiddleware,
allow_origins=os.getenv("ALLOW_ORIGINS", "*").split(","),
allow_methods=["GET", "POST", "PATCH", "DELETE"],
allow_headers=["Content-Type", "Aloy-App-ID", "Aloy-User-ID"],
expose_headers=["X-Total-Count"],
)
app.add_middleware(GZipMiddleware)
app.include_router(v1.router)
@app.get("/health")
async def health():
return "ok"