多任务操作数据库时:2006, 'MySQL server has gone away'

查到Django官网中:https://code.djangoproject.com/ticket/21597


这不是数据库的问题。

If you hit this problem and don't want to understand what's going on, don't reopen this ticket, just do this:

RECOMMENDED SOLUTION: close the connection with 

    from django.db import connection

    connection.close() 

when you know that your program is going to be idle for a long time.

CRAPPY SOLUTION: increase wait_timeout so it's longer than the maximum idle time of your program.

In this context, idle time is the time between two successive database queries.



def main():
    q = Queue()
    p_1 = Process(target=func1, args=(selected, q))
    p_2 = Process(target=func2, args=(request, q))
    p_1.start()
    p_2.start()
    q.put(2)
    return
执行过程:
1)main:开启两个进程;往队列q里写入2;return
2)func1 和 func2 开始while循环,
func1先从q中读到2,于是执行func11,
func11之后往q中写3;
func2在1秒后开始从q中读到3,开始执行func22。
def func1(dc_id, q=None):
    while 1:
        value = q.get(True)
        time.sleep(1)
        if value == 2:
            func11(dc_id) # 操作数据库
            q.put(3)
            break
def func2(request, q):
    while 1:
        time.sleep(1)
        value = q.get(True)
        if value == 3:
            func22(request) # 操作数据库
            break
def func11(dc_id):
    if not is_connection_usable():
        connection.close()

    ...操作数据库...
def func22(dc_id):
    if not is_connection_usable():
        connection.close()

    ...操作数据库...
from django.db import connection
def is_connection_usable():
    try:
        print 'connection', connection.connection.ping()
    except:
        return False
    else:
        return True
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值