为什么这个循环不会每五秒显示更新的对象数? [英] Why doesn't this loop display an updated object count every five seconds?

查看:118
本文介绍了为什么这个循环不会每五秒显示更新的对象数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个python代码每5秒输出一次事件:

I use this python code to output the number of Things every 5 seconds:

def my_count():     
    while True:
        print "Number of Things: %d" % Thing.objects.count()
        time.sleep(5)

my_count() 

如果另一个进程在my_count()正在运行时生成新的Thing,my_count()将继续打印相同的数字,甚至尽管数据库中现在已经发生了变化。 (但是如果我杀死my_count()并重新启动它,它将显示新的Thing计数。)

If another process generates a new Thing while my_count() is running, my_count() will keep printing the same number, even though it now has changed in the database. (But if I kill my_count() and restart it, it will display the new Thing count.)

事物存储在MYSQL innodb数据库中,此代码运行在ubuntu。

Things are stored in a MYSQL innodb database, and this code runs on ubuntu.

为什么my_count()不显示新的Thing.objects.count()而不重新启动?

Why won't my_count() display the new Thing.objects.count() without being restarted?

推荐答案

因为Python DB API在AUTOCOMMIT = OFF模式下是默认的,并且(至少对于MySQLdb)在REPEATABLE READ隔离级别。这意味着幕后你有一个持续的数据库事务(InnoDB是事务引擎),其中第一次访问给定行(或者甚至表,我不确定)修复了该资源的查看,剩余部分交易。

Because Python DB API is by default in AUTOCOMMIT=OFF mode, and (at least for MySQLdb) on REPEATABLE READ isolation level. This means that behind the scenes you have an ongoing database transaction (InnoDB is transactional engine) in which the first access to given row (or maybe even table, I'm not sure) fixes "view" of this resource for the remaining part of the transaction.

为了防止这种情况,您必须刷新当前的交易:

To prevent this behaviour, you have to 'refresh' current transaction:

  from django.db import transaction


  @transaction.autocommit  
  def my_count():     
      while True:
          transaction.commit()
          print "Number of Things: %d" % Thing.objects.count()
          time.sleep(5)

- 请注意, transaction.autocommit 装饰器只用于进入事务管理模式(这也可以使用transaction.enter_transaction_management / leave_tran手动完成saction_managemen函数)。

-- note that the transaction.autocommit decorator is only for entering transaction management mode (this could also be done manually using transaction.enter_transaction_management/leave_transaction_managemen functions).

还有一件事 - 要知道 - Django的自动提交与数据库中的自动提交功能不一样 - 它完全独立。但是这个问题超出了范围。

One more thing - to be aware - Django's autocommit is not the same autocommit you have in database - it's completely independent. But this is out of scope for this question.

这里是一个孪生答案一个类似的问题。

Here is a "twin answer" to a similar question.

这篇关于为什么这个循环不会每五秒显示更新的对象数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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