From 7afa49ddec82173db2b031000884ef1948898073 Mon Sep 17 00:00:00 2001 From: Luke Kuzmish Date: Sun, 19 Nov 2023 13:36:02 -0500 Subject: [PATCH 1/5] handle uncaught exception to include CORS middleware --- boaviztapi/main.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/boaviztapi/main.py b/boaviztapi/main.py index 571bd509..14fb53d9 100644 --- a/boaviztapi/main.py +++ b/boaviztapi/main.py @@ -7,6 +7,8 @@ from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from mangum import Mangum +from starlette.requests import Request +from starlette.responses import Response from boaviztapi.routers import iot_router from boaviztapi.routers.component_router import component_router @@ -25,11 +27,22 @@ stage = os.environ.get('STAGE', None) openapi_prefix = f"/{stage}" if stage else "/" app = FastAPI(root_path=openapi_prefix) # Here is the magic -version = toml.loads(open(os.path.join(os.path.dirname(__file__), '../pyproject.toml'), 'r').read())['tool']['poetry']['version'] - +version = toml.loads(open(os.path.join(os.path.dirname(__file__), '../pyproject.toml'), 'r').read())['tool']['poetry'][ + 'version'] origins = json.loads(os.getenv("ALLOWED_ORIGINS", '["*"]')) + +# Ensure that even an uncaught exception includes CORS headers. +async def catch_exceptions_middleware(request: Request, call_next): + try: + return await call_next(request) + except Exception as e: + return Response(str(e), status_code=500) + + +app.middleware('http')(catch_exceptions_middleware) + app.add_middleware( CORSMiddleware, allow_origins=origins, @@ -46,11 +59,10 @@ app.include_router(consumption_profile) app.include_router(utils_router) - if __name__ == '__main__': import uvicorn - uvicorn.run('main:app', host='localhost', port=5000, reload=True, debug=True) + uvicorn.run('main:app', host='localhost', port=5000, reload=True) @app.on_event("startup") From c02e4937896728237b02b8a19d53661108aeb776 Mon Sep 17 00:00:00 2001 From: Luke Kuzmish Date: Sun, 19 Nov 2023 15:02:47 -0500 Subject: [PATCH 2/5] formatting --- boaviztapi/main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/boaviztapi/main.py b/boaviztapi/main.py index 14fb53d9..b27d28bb 100644 --- a/boaviztapi/main.py +++ b/boaviztapi/main.py @@ -27,8 +27,7 @@ stage = os.environ.get('STAGE', None) openapi_prefix = f"/{stage}" if stage else "/" app = FastAPI(root_path=openapi_prefix) # Here is the magic -version = toml.loads(open(os.path.join(os.path.dirname(__file__), '../pyproject.toml'), 'r').read())['tool']['poetry'][ - 'version'] +version = toml.loads(open(os.path.join(os.path.dirname(__file__), '../pyproject.toml'), 'r').read())['tool']['poetry']['version'] origins = json.loads(os.getenv("ALLOWED_ORIGINS", '["*"]')) @@ -59,10 +58,11 @@ async def catch_exceptions_middleware(request: Request, call_next): app.include_router(consumption_profile) app.include_router(utils_router) + if __name__ == '__main__': import uvicorn - uvicorn.run('main:app', host='localhost', port=5000, reload=True) + uvicorn.run('main:app', host='localhost', port=5000, reload=True, debug=True) @app.on_event("startup") From 0507a8980ef911fe8266b93d29530c6ab14b967c Mon Sep 17 00:00:00 2001 From: Luke Kuzmish Date: Mon, 20 Nov 2023 16:04:23 -0500 Subject: [PATCH 3/5] log stacktrace --- boaviztapi/main.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/boaviztapi/main.py b/boaviztapi/main.py index b27d28bb..294e7cc0 100644 --- a/boaviztapi/main.py +++ b/boaviztapi/main.py @@ -1,4 +1,5 @@ import json +import logging import markdown import toml @@ -28,6 +29,7 @@ openapi_prefix = f"/{stage}" if stage else "/" app = FastAPI(root_path=openapi_prefix) # Here is the magic version = toml.loads(open(os.path.join(os.path.dirname(__file__), '../pyproject.toml'), 'r').read())['tool']['poetry']['version'] +logger = logging.getLogger(__name__) origins = json.loads(os.getenv("ALLOWED_ORIGINS", '["*"]')) @@ -37,6 +39,7 @@ async def catch_exceptions_middleware(request: Request, call_next): try: return await call_next(request) except Exception as e: + logger.exception(e, exc_info=True) return Response(str(e), status_code=500) From 9cdeea23f3da5540ae3cc4c816a68d69813ada7e Mon Sep 17 00:00:00 2001 From: Luke Kuzmish Date: Tue, 21 Nov 2023 06:43:39 -0500 Subject: [PATCH 4/5] remove context --- boaviztapi/main.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/boaviztapi/main.py b/boaviztapi/main.py index 294e7cc0..be67756f 100644 --- a/boaviztapi/main.py +++ b/boaviztapi/main.py @@ -1,6 +1,7 @@ import json import logging +import anyio import markdown import toml from fastapi.middleware.cors import CORSMiddleware @@ -29,7 +30,7 @@ openapi_prefix = f"/{stage}" if stage else "/" app = FastAPI(root_path=openapi_prefix) # Here is the magic version = toml.loads(open(os.path.join(os.path.dirname(__file__), '../pyproject.toml'), 'r').read())['tool']['poetry']['version'] -logger = logging.getLogger(__name__) +_logger = logging.getLogger(__name__) origins = json.loads(os.getenv("ALLOWED_ORIGINS", '["*"]')) @@ -39,8 +40,12 @@ async def catch_exceptions_middleware(request: Request, call_next): try: return await call_next(request) except Exception as e: - logger.exception(e, exc_info=True) - return Response(str(e), status_code=500) + # ignore anyio's EndOfStream exception traceback which just clutters up logs + if isinstance(e.__context__, anyio.EndOfStream): + e.__suppress_context__ = True + + _logger.exception(str(e), exc_info=e) + return Response('Internal Server Error', status_code=500) app.middleware('http')(catch_exceptions_middleware) @@ -61,11 +66,10 @@ async def catch_exceptions_middleware(request: Request, call_next): app.include_router(consumption_profile) app.include_router(utils_router) - if __name__ == '__main__': import uvicorn - uvicorn.run('main:app', host='localhost', port=5000, reload=True, debug=True) + uvicorn.run('main:app', host='127.0.0.1', port=5000, reload=True) @app.on_event("startup") From 422b294786ff84e7f19c30c8e6ad248b1b621d3d Mon Sep 17 00:00:00 2001 From: Luke Kuzmish <42181698+cosmastech@users.noreply.github.com> Date: Tue, 21 Nov 2023 10:03:01 -0500 Subject: [PATCH 5/5] switch host back to localhost --- boaviztapi/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/boaviztapi/main.py b/boaviztapi/main.py index be67756f..c2236191 100644 --- a/boaviztapi/main.py +++ b/boaviztapi/main.py @@ -69,7 +69,7 @@ async def catch_exceptions_middleware(request: Request, call_next): if __name__ == '__main__': import uvicorn - uvicorn.run('main:app', host='127.0.0.1', port=5000, reload=True) + uvicorn.run('main:app', host='localhost', port=5000, reload=True) @app.on_event("startup")