在Django中捕获OperationalError 1040

时间:2014-08-25 19:57:25

标签: python mysql django web

我在共享服务器上运行我的Django网站,因此我的用户不时会收到内部服务器错误500页,因为特定的OperationalError异常将自己标识为(1040, "Too Many Connections")。我的handler500 = 'myapp.views.error500'中有一个自定义500.html页面和urls.py - 我的视图中的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})

我从OperationalError模块导入MySQLdb。但这会将所有MySQL错误归因于" Too Many Connections" - 我怎么才能抓住1040错误?我怎么能测试它而不用等待看到共享的MySQL服务器是否在我正在浏览自己的网站时过载?

1 个答案:

答案 0 :(得分:-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个...