如何在Django中设置数据库连接超时 [英] How to set timeout for database connection in django

查看:976
本文介绍了如何在Django中设置数据库连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有mysql数据库作为django的引擎。 Django通过fastcgi认为nginx在1分钟内超时(此后nginx说 504网关超时)。

I have mysql database as engine for django. Django works thought nginx via fastcgi with timeout in 1 min (after that nginx says "504 gateway time-out").

如果数据库出现故障,django会尝试重新连接DB并等待它的响应。并且等待响应时间过长(超过1分钟),nginx会向客户端返回504错误代码。

If database gone down, django is trying reconnect to DB and waiting for response from it. And waiting for response too long (more than 1 minute) that nginx returns to client the 504 error code.

如何在Django中设置数据库连接超时?还有什么正确的方法来处理此事件并返回给客户一个漂亮的页面,上面显示抱歉数据库已停用。请稍后再试,而不是技术性504错误页面?

How to set timeout for db connecton in django? And what the right way to handle this event and return to client a pretty page with "Sorry database is out of service now. Please try later" instead of technical 504 error page?

推荐答案

您可以使用选项您的数据库设置的字典。

You can use the OPTIONS dictionary of your DATABASES setting.

选项名称取决于您的数据库后端,但对于PostgreSQL,它将为 connect_timeout

The option name depends on your DB backend, but for PostgreSQL it would be connect_timeout:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        …
        'OPTIONS': {
            'connect_timeout': 5,
        }
    }
}

这篇关于如何在Django中设置数据库连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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