【问题标题】:Django resetting Postgres connectionDjango 重置 Postgres 连接
【发布时间】:2013-05-30 16:34:21
【问题描述】:

我正在运行 Django 1.4 并使用 psycopg2 和 Postgres 9.2.4。

在我的 Postgres 日志中

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

下面是导致它的代码。这是一个管理命令。我已经做了研究,我能找到的一切都是关于 django 交易的。我没有使用它们,我也尝试了以下方法无济于事。

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

我还阅读了有关 oom-killer 的可能性,但我仍然有大量内存并且它不在日志中。

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)

任何帮助将不胜感激!

【问题讨论】:

    标签: django postgresql psycopg2


    【解决方案1】:

    这似乎是 Django 没有在管理命令中为您关闭数据库连接的特定问题。

    解决方法是在 handle() 结束时显式关闭数据库连接,如下所示:

    import ...
    from django import db
    
    
    class Command(BaseCommand):
        help = 'Update the Entry hits'
    
        def handle(self, *args, **options):
            ...
            db.close_connection() 
    

    【讨论】:

    • 这不是问题。我在命令运行时收到此错误,而不是在命令结束时...
    • @Cerin 我有一个用于单元测试的元命令,它会调用导致此问题的子命令,并在子命令末尾关闭数据库是问题所在。也许您的问题源于另一个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多