Django预关机钩关闭挂pymongo连接 [英] Django pre-shutdown hook to close hanging pymongo connection

查看:149
本文介绍了Django预关机钩关闭挂pymongo连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django项目中使用pymongo,最近我开始遇到一个问题,在退出主Django进程(甚至通过管理命令)时,pymongo连接将挂起,进程永远不会出口。显然,堆栈中有一些错误,但是现在最好的解决方案似乎是在Django退出之前明确地关闭连接。



那么Django是否提供了一个预关闭信号或钩子?



BTW:my连接代码,以防您感兴趣。

从$ d code>从django.conf导入设置
从pymongo import ReplicaSetConnection,ReadPreference

conn = ReplicaSetConnection(
hosts_or_uri = settings.MONGO ['HOST'],
replicaSet = settings.MONGO ['REPLICASET'],
safe = settings.MONGO .get('SAFE',False),
journal = settings.MONGO.get('JOURNAL',False),
read_preference = ReadPreference.PRIMARY


db = getattr(conn,settings.MONGO ['DB'])

(作为一个点好奇,这是在pymongo进行连接池的正确方法吗?)

解决方案

虽然这不会解决您的问题,该挂机于2012年7月推出,致力于pymongo: https://github.com/mongodb/mongo-python-driver/commit/1fe6029c5d78eed64fcb2a6d368d9cdf8756d2f4#commitcomment-1820334



具体来说,它只影响ReplicaSetConnections。他们给出的答案是调用connection.close(),但正如您在问题中正确指出的那样,关闭连接没有很好的钩子。



我相信您可以在每个请求结束时安全地关闭连接。 Django已经为此连接到数据库的ORM。这就是为什么他们推荐使用像pgbouncer这样的连接池,所以重新连接到postgres是即时的。 Pymongo内置了一个连接池,因此可以随意重新连接。


I'm using pymongo in a Django project, and recently I've began to run into a problem where, upon exiting the main Django process (even through a management command) the pymongo connection will hang, and the process will never exit. Obviously, there's something wrong somewhere in the stack, but for now the best solution seems to be to explicitly close the connection before Django exits.

So: is there a pre-shutdown signal or hook that Django provides for this?

BTW: my connection code in case you're interested.

from django.conf import settings
from pymongo import ReplicaSetConnection, ReadPreference

conn = ReplicaSetConnection(
    hosts_or_uri=settings.MONGO['HOST'],
    replicaSet=settings.MONGO['REPLICASET'],
    safe=settings.MONGO.get('SAFE', False),
    journal=settings.MONGO.get('JOURNAL', False),
    read_preference=ReadPreference.PRIMARY
)

db = getattr(conn, settings.MONGO['DB'])

(and as a point of curiousity, is this the right way to do connection pooling in pymongo?)

解决方案

While this won't fix your issue, the hang was introduced in July 2012 on this commit to pymongo: https://github.com/mongodb/mongo-python-driver/commit/1fe6029c5d78eed64fcb2a6d368d9cdf8756d2f4#commitcomment-1820334.

Specifically, it only affects ReplicaSetConnections. The answer they gave is to call connection.close(), but as you correctly pointed out in your question, there is no good hook to close the connection.

I believe that you can safely close the connection at the end of every request. Django already does this for its ORM connections to the db. This is why they recommending using a connection pool like pgbouncer, so reconnecting to postgres is instant. Pymongo has a connection pool built in, so reconnect at will.

这篇关于Django预关机钩关闭挂pymongo连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆