Adam P
Adam P

Reputation: 331

Django resetting Postgres connection

I'm running Django 1.4 and using psycopg2 along with Postgres 9.2.4.

In my Postgres logs

2013-05-30 16:20:22 UTC LOG: could not receive data from client: Connection reset by peer

Below is the code that causes it. It is a management command. I've done research and everything I can find refers to django transactions. I'm not using them and I've tried the following to no avail as well.

['DATABASES']['default']['OPTIONS']['autocommit'] = True

I've also read about possibility of the oom-killer but I still have tons of memory and its not in the logs.

import sys

from django.core.mail import mail_admins
from django.core.management.base import BaseCommand
from django.db.models import F

from redis_cache import get_redis_connection


    class Command(BaseCommand):
        help = 'Update the Entry hits'

        def handle(self, *args, **options):
            from vplatform.content.models import Entry

            redis_conn = get_redis_connection('default')
            hits_for_obj = dict()
            hit_len = int(redis_conn.llen('entry-hits'))

            while (hit_len > 0):
                hit_len = hit_len - 1
                obj_id = redis_conn.rpop('entry-hits')
                hits_for_obj[obj_id] = hits_for_obj.get(obj_id, 0) + 1

            for obj_id, hits in hits_for_obj.items():
                try:
                    entry = Entry.objects.get(pk=obj_id)
                    entry.hit_count = F('hit_count') + hits
                    entry.save()
                except:
                    e = sys.exc_info()[0]
                    message = "Error: %s" % e
                    mail_admins('Update hits error', message)

Any help would be greatly appreciated!

Upvotes: 2

Views: 1597

Answers (1)

Adam P
Adam P

Reputation: 331

It seems this was a specific problem with Django not closing the database connection for you within management commands.

The fix was to explicitly close the database connection at the end of handle() like so:

import ...
from django import db


class Command(BaseCommand):
    help = 'Update the Entry hits'

    def handle(self, *args, **options):
        ...
        db.close_connection() 

Upvotes: 1

Related Questions