2

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!

1 Answer 1

1

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() 
Sign up to request clarification or add additional context in comments.

2 Comments

This isn't the issue. I get this error while the command is running, not at the end of the command...
@Cerin I had a meta command for unit testing that would call sub-commands that caused this issue and closing the database at the end of the sub-commands was the issue. Perhaps your issue stems from a different issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.