generated from Ubademy/ubademy.service.pytemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
77 lines (63 loc) · 1.89 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
import ast
import logging
import os
from logging import config
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from starlette import status
from starlette.requests import Request
from starlette.responses import Response
from app.router.router import Router
from app.router.router_exception import InvalidMicroserviceError
config.fileConfig("logging.conf", disable_existing_loggers=False)
logger = logging.getLogger(__name__)
app = FastAPI(title="gateway")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
try:
microservices = ast.literal_eval(os.environ["MICROSERVICES"])
except KeyError as e:
microservices = {}
@app.api_route(
"/{full_path:path}",
status_code=status.HTTP_200_OK,
methods=["GET", "POST", "PUT", "DELETE", "PATCH"],
tags=["gateway"],
)
async def catch_all(request: Request, response: Response, full_path: str):
try:
logger.info(full_path)
router = Router(microservices=microservices)
caller = router.get_service_caller(path=full_path)
service_response = await caller.call_with_request(request=request)
except InvalidMicroserviceError as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=e.message,
)
except Exception as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
try:
response.status_code = service_response.status_code
r = service_response.json()
except Exception as e:
logger.error(e)
r = {}
return r
@app.options(
"/{full_path:path}",
status_code=status.HTTP_200_OK,
tags=["gateway"],
)
async def options(full_path: str):
logger.info(full_path)
return "options"