django关连mysql_如何在Django中测试关闭数据库连接的方法?

嗯,我不确定这是否是最好的答案,但由于这个问题到目前为止没有回复,我将发布我最终用于后代的解决方案:

我创建了一个辅助函数,在关闭连接之前检查我们当前是否处于原子块中:

import django

from django.db import connection

from my_app import models

def close_connection():

"""Closes the connection if we are not in an atomic block.

The connection should never be closed if we are in an atomic block, as

happens when running tests as part of a django TestCase. Otherwise, closing

the connection is important to avoid a connection time out after long actions.

Django does not automatically refresh a connection which has been closed

due to idleness (this normally happens in the request start/finish part

of a webapp's lifecycle, which this process does not have), so we must

do it ourselves if the connection goes idle due to stuff taking a really

long time.

"""

if not connection.in_atomic_block:

connection.close()

def my_process():

django.setup()

while (True):

do_stuff()

close_connection()

models.MyDjangoModel().save()

正如评论所述,close_connection阻止了connection.close在测试中被调用,因此我们不再破坏测试事务。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值