#24810: Reopen database connection automatically when no transaction is active
-------------------------------------+-------------------------------------
Reporter: Aymeric Augustin | Owner: nobody
Type: New feature | Status: new
Component: Database layer | Version: dev
(models, ORM) |
Severity: Normal | Resolution:
Keywords: | Triage Stage: Accepted
Has patch: 1 | Needs documentation: 0
Needs tests: 1 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by HaukurPall):
In our system we use FastAPI with uvicorn and the Django ORM (using
psycopg). When the database is restarted Django does not reinitialize the
connection and it is broken until the system is restarted. psycopg reports
the connection as BAD but it is not reestablished.
I was able to resolve the issue by call close_old_connections **but** care
needs to be taken in how it is done via FastAPI.
My solution was to create an async exception_handler and wrap the
close_old_connections in a sync_to_async.
If the close_old_connections is not wrapped, it still runs but it has no
observable effect. This function does call BaseDatabaseWrapper.close()
which is marked as async_unsafe but still allows the close_old_connections
to be called from async context. I don't understand how that is possible.
I also tried making the exception_handler synchronous, iterate over the
connections and call BaseDatabaseWrapper.connect() on the default
connection (we only have one) but then I noticed that the underlying
threads started reporting different memory addresses for the connection.
I.e. the underlying psycopg connection remains the same (BAD) but in my
exception_handler the connection is ok and the connection is restarted,
with a new connection object which is **not** used by other parts of
django.
So this seems to also be a threading issue?
--
Ticket URL: <https://code.djangoproject.com/ticket/24810#comment:21>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/01070191b2a7d855-64b2bf56-e330-4d75-9e85-8f055b157dc8-000000%40eu-central-1.amazonses.com.