在Django中捕获OperationalError 1040

1 投票
1 回答
733 浏览
提问于 2025-04-18 18:29

我在一个共享服务器上运行我的Django网站,所以有时候我的用户会遇到一个叫做“内部服务器错误500”的页面,原因是出现了一个特定的操作错误,显示为 (1040, "Too Many Connections")。我有一个自定义的500.html页面,并在我的 urls.py 文件中设置了 handler500 = 'myapp.views.error500' -- 在我的视图中,error500 方法是:

def error500(request):
    exctype, value = sys.exc_info()[:2]
    msg = ''
    if exctype == OperationalError:
        msg = 'We\'re busy at the moment -- please reload this page in a little while.'
    return render_to_response('500.html', {'msg': msg})

在这里,我从 MySQLdb 模块中导入了 OperationalError。但是这样做会把所有的MySQL错误都归结为“连接过多” -- 我该如何只捕捉到1040错误呢?还有,我该如何测试这个错误,而不需要等到共享的MySQL服务器过载时,正好我在浏览自己的网站?

1 个回答

-1

这是我找到的解决办法:

def error500(request):
    exctype, value = sys.exc_info()[:2]
    msg = ''
    if exctype == OperationalError and value.args[0] == 1040:
        msg = 'We\'re busy at the moment -- please reload this page in a little while.'
    return render_to_response('500.html', {'msg': msg})

我写了一个bash脚本,测试了打开151个连接(这是最大连接数)到我的MySQL服务器,然后我去访问我的网页,试着打开第152个连接...

撰写回答