From: Michael Tremer Date: Fri, 9 Jan 2026 17:02:37 +0000 (+0000) Subject: api: Add a middleware to correctly close database sessions X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=3075de9aab1c69057016aa6bc1735a3d29006ae8;p=dbl.git api: Add a middleware to correctly close database sessions Signed-off-by: Michael Tremer --- diff --git a/Makefile.am b/Makefile.am index 4ffe659..20bef28 100644 --- a/Makefile.am +++ b/Makefile.am @@ -70,6 +70,7 @@ dist_pkgpython_api_PYTHON = \ src/dnsbl/api/__init__.py \ src/dnsbl/api/domains.py \ src/dnsbl/api/lists.py \ + src/dnsbl/api/middlewares.py \ src/dnsbl/api/reports.py pkgpython_apidir = $(pkgpythondir)/api diff --git a/src/dnsbl/api/__init__.py b/src/dnsbl/api/__init__.py index b35297f..4289cd6 100644 --- a/src/dnsbl/api/__init__.py +++ b/src/dnsbl/api/__init__.py @@ -24,6 +24,9 @@ import fastapi.security # Import the backend from .. import Backend +# Import middlewares +from . import middlewares + # Initialize the app app = fastapi.FastAPI( title = "IPFire DNSBL API", @@ -31,6 +34,7 @@ app = fastapi.FastAPI( # Enable debug mode debug = True, ) +app.add_middleware(middlewares.DatabaseSessionMiddleware) # Initialize the backend backend = app.state.backend = Backend( diff --git a/src/dnsbl/api/middlewares.py b/src/dnsbl/api/middlewares.py new file mode 100644 index 0000000..534731b --- /dev/null +++ b/src/dnsbl/api/middlewares.py @@ -0,0 +1,29 @@ +############################################################################### +# # +# dnsbl - A DNS Blocklist Compositor For IPFire # +# Copyright (C) 2026 IPFire Development Team # +# # +# This program is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# This program is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +############################################################################### + +import fastapi + +class DatabaseSessionMiddleware(fastapi.applications.BaseHTTPMiddleware): + async def dispatch(self, request: fastapi.Request, call_next): + backend = request.app.state.backend + + # Acquire a new database session and process the request + with backend.db.session() as session: + return await call_next(request)