Monday, September 30, 2019

Re: Database connection closed after each request?

Hi Mike,
I tried with custom persistent connection, but results in same error. My environment is Django + postgres + nginx + gunicorn

On Saturday, August 29, 2009 at 5:38:58 PM UTC+5:30, Mike wrote:

I made some small custom psycopg2 backend that implements persistent
connection using global variable. With this I was able to improve the
amount of requests per second from 350 to 1600 (on very simple page
with few selects) Just save it in the file called in any
directory (e.g. postgresql_psycopg2_persistent) and set in settings:

DATABASE_ENGINE to projectname.postgresql_psycopg2_persistent

Here is a source:

# Custom DB backend postgresql_psycopg2 based
# implements persistent database connection using global variable

from django.db.backends.postgresql_psycopg2.base import DatabaseError,
DatabaseWrapper as BaseDatabaseWrapper, \
from psycopg2 import OperationalError

connection = None

class DatabaseWrapper(BaseDatabaseWrapper):
    def _cursor(self, *args, **kwargs):
        global connection
        if connection is not None and self.connection is None:
            try: # Check if connection is alive
                connection.cursor().execute('SELECT 1')
            except OperationalError: # The connection is not working,
need reconnect
                connection = None
                self.connection = connection
        cursor = super(DatabaseWrapper, self)._cursor(*args, **kwargs)
        if connection is None and self.connection is not None:
            connection = self.connection
        return cursor

    def close(self):
        if self.connection is not None:
            self.connection = None

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit

No comments:

Post a Comment