-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path__init__.py
More file actions
66 lines (54 loc) · 2.16 KB
/
__init__.py
File metadata and controls
66 lines (54 loc) · 2.16 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 logging
from typing import Union
from fastapi import FastAPI, Request
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware
from starlette.responses import JSONResponse
from starlette_prometheus import PrometheusMiddleware, metrics
from common import AppConfig, application_init
from http_app import context
from http_app.routes import init_routes
def create_app(
test_config: Union[AppConfig, None] = None,
) -> FastAPI:
app_config = test_config or AppConfig()
"""
The config is submitted here at runtime, this means
that we cannot declare a function to be used with
FastAPI dependency injection system because Depends
is evaluated before this function is called.
A context variable will achieve the same purpose.
"""
context.app_config.set(app_config)
application_init(app_config)
app = FastAPI(
debug=app_config.DEBUG,
title=app_config.APP_NAME,
)
init_exception_handlers(app)
init_routes(app)
"""
OpenTelemetry prometheus exporter does not work together with automatic
instrumentation, for now we keep the prometheus middleware even if
having 2 different middlewares will add overhead.
"""
app.add_middleware(PrometheusMiddleware)
app.add_route("/metrics/", metrics)
"""
OpenTelemetry middleware has to be the last one to make sure the
tracing data handling is the outermost logic
Some typing issues to be addressed in OpenTelemetry but it works.
"""
app.add_middleware(OpenTelemetryMiddleware) # type: ignore
return app
def init_exception_handlers(app: FastAPI) -> None:
# This is a catch-all middleware for unhandled exceptions
# other Exception handlers should be initialised using
# the @app.exception_handler decorator
# https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers
@app.middleware("http")
async def add_exception_middleware(request: Request, call_next):
try:
return await call_next(request)
except Exception as e:
logging.exception(e)
return JSONResponse({"error": "Internal server error"}, status_code=500)