Skip to content

Commit ca6c4ba

Browse files
committed
Removing flask dependency from package
1 parent 1dcd6ea commit ca6c4ba

File tree

2 files changed

+61
-49
lines changed

2 files changed

+61
-49
lines changed

middleware/__init__.py

+60-47
Original file line numberDiff line numberDiff line change
@@ -59,57 +59,70 @@ def _uninstrument(self, **kwargs):
5959
ExceptionInstrumentor().instrument()
6060

6161
# Automatic exception handling for flask
62-
from flask import Flask, request
63-
from flask.signals import got_request_exception, appcontext_pushed
64-
import traceback
65-
66-
def _capture_exception(sender, exception, **extra):
67-
exc_type, exc_value, exc_traceback = sys.exc_info() # Get exception details
68-
if exc_type and exc_value and exc_traceback:
69-
record_exception(exc_type, exc_value, exc_traceback)
70-
else:
71-
print("Unable to capture exception details.")
62+
try:
63+
from flask import Flask, request
64+
from flask.signals import got_request_exception, appcontext_pushed
65+
except ImportError:
66+
Flask = None
67+
got_request_exception = None
68+
appcontext_pushed = None
69+
70+
if Flask and got_request_exception and appcontext_pushed:
71+
def _capture_exception(sender, exception, **extra):
72+
exc_type, exc_value, exc_traceback = sys.exc_info() # Get exception details
73+
if exc_type and exc_value and exc_traceback:
74+
record_exception(exc_type, exc_value, exc_traceback)
75+
else:
76+
print("Unable to capture exception details.")
7277

73-
def try_register_flask_handler(app: Flask):
74-
"""Registers the exception handler using Flask signals."""
75-
got_request_exception.connect(_capture_exception, app)
76-
print("✅ Flask error handler registered via signal.")
78+
def try_register_flask_handler(app: Flask):
79+
"""Registers the exception handler using Flask signals."""
80+
got_request_exception.connect(_capture_exception, app)
81+
print("✅ Flask error handler registered via signal.")
7782

78-
def _auto_register(sender, **extra):
79-
"""Automatically registers the handler when a Flask app context is pushed."""
80-
try_register_flask_handler(sender)
83+
def _auto_register(sender, **extra):
84+
"""Automatically registers the handler when a Flask app context is pushed."""
85+
try_register_flask_handler(sender)
8186

82-
# Connect to Flask's appcontext_pushed to register automatically
83-
appcontext_pushed.connect(_auto_register)
87+
# Connect to Flask's appcontext_pushed to register automatically
88+
appcontext_pushed.connect(_auto_register)
8489

8590

8691
# Automatic exception handling for FastAPI
87-
from starlette.middleware.base import BaseHTTPMiddleware
88-
from starlette.requests import Request
89-
from starlette.responses import JSONResponse
90-
91-
class ExceptionMiddleware(BaseHTTPMiddleware):
92-
"""Middleware to catch unhandled exceptions globally."""
93-
async def dispatch(self, request: Request, call_next):
94-
try:
95-
return await call_next(request)
96-
except Exception as exc:
97-
exc_type, exc_value, exc_traceback = exc.__class__, exc, exc.__traceback__
98-
record_exception(exc_type, exc_value, exc_traceback)
92+
try:
93+
from starlette.middleware.base import BaseHTTPMiddleware
94+
from starlette.requests import Request
95+
from starlette.responses import JSONResponse
96+
from fastapi import FastAPI
97+
except ImportError:
98+
BaseHTTPMiddleware = None
99+
Request = None
100+
JSONResponse = None
101+
FastAPI = None
102+
103+
if BaseHTTPMiddleware and FastAPI:
104+
class ExceptionMiddleware(BaseHTTPMiddleware):
105+
"""Middleware to catch unhandled exceptions globally."""
106+
async def dispatch(self, request: Request, call_next):
107+
try:
108+
return await call_next(request)
109+
except Exception as exc:
110+
exc_type, exc_value, exc_traceback = exc.__class__, exc, exc.__traceback__
111+
record_exception(exc_type, exc_value, exc_traceback)
112+
113+
return JSONResponse(
114+
status_code=500,
115+
content={"detail": "Internal Server Error"},
116+
)
99117

100-
return JSONResponse(
101-
status_code=500,
102-
content={"detail": "Internal Server Error"},
103-
)
104-
105-
from fastapi import FastAPI
106-
# from starlette.middleware import ExceptionMiddleware
107-
108-
_original_init = FastAPI.__init__
109-
110-
def new_fastapi_init(self, *args, **kwargs):
111-
_original_init(self, *args, **kwargs)
112-
print("✅ FastAPI instance created, registering ExceptionMiddleware.")
113-
self.add_middleware(ExceptionMiddleware)
114-
115-
FastAPI.__init__ = new_fastapi_init
118+
from fastapi import FastAPI
119+
# from starlette.middleware import ExceptionMiddleware
120+
121+
_original_init = FastAPI.__init__
122+
123+
def new_fastapi_init(self, *args, **kwargs):
124+
_original_init(self, *args, **kwargs)
125+
print("✅ FastAPI instance created, registering ExceptionMiddleware.")
126+
self.add_middleware(ExceptionMiddleware)
127+
128+
FastAPI.__init__ = new_fastapi_init

pyproject.toml

+1-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "middleware-io"
7-
version = "2.1.2rc7"
7+
version = "2.1.2rc8"
88
requires-python = ">=3.8"
99
description = "Middleware's APM tool enables Python developers to effortlessly monitor their applications, gathering distributed tracing, metrics, logs, and profiling data for valuable insights and performance optimization."
1010
authors = [{ name = "middleware-dev" }]
@@ -21,7 +21,6 @@ keywords = [
2121
]
2222
dependencies =[
2323
"distro==1.9.0",
24-
"flask==2.3.2",
2524
"opentelemetry-api==1.27.0",
2625
"opentelemetry-exporter-otlp-proto-grpc==1.27.0",
2726
"opentelemetry-instrumentation==0.48b0",

0 commit comments

Comments
 (0)