Skip to content

Conversation

bmispelon
Copy link
Member

eb16ed0 removed (among a lot of other things) a call to close_old_connections(), mostly because I hadn't understood what that was doing exactly.
Since then I've been kept awake at night with the sense of dread that old database connections were piling up unclosed on Django's server.

So I wrote this wsgi middleware that should hopefully restore balance in the universe, or at least close db connections.

eb16ed0 removed (among a lot of other things)
a call to close_old_connections(), mostly because I hadn't understood what that
was doing exactly.
Since then I've been kept awake at night with the sense of dread that
old database connections were piling up unclosed on Django's server.

So I wrote this wsgi middleware that should hopefully restore balance
in the universe, or at least close db connections.
@bmispelon bmispelon requested a review from felixxm February 10, 2024 11:56
Comment on lines +4 to +22
class DjangoDBManagementMiddleware:
"""
A simple WSGI middleware that manually manages opening/closing db connections.

Django normally does that as part of its own middleware chain, but we're using Trac's middleware
so we must do this by hand.
This hopefully prevents open connections from piling up.
"""

def __init__(self, application):
self.application = application

def __call__(self, environ, start_response):
request_started.send(sender=self.__class__)
try:
for data in self.application(environ, start_response):
yield data
finally:
request_finished.send(sender=self.__class__)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this would make a lovely talk.

Copy link
Member

@felixxm felixxm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bmispelon Thanks 👍

@felixxm felixxm merged commit c845c54 into django:main Feb 14, 2024
@felixxm
Copy link
Member

felixxm commented Feb 14, 2024

Deployed.

@bmispelon bmispelon deleted the close-db-connections branch February 14, 2024 16:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants