为什么django会在新创建的对象上给我一个ObjectDoesNotExist错误?

时间:2013-06-13 18:21:58

标签: python mysql django

我在测试一些使用django处理订单的代码时遇到了这个问题。尝试加载(通过id)新创建的记录时,我收到“ObjectDoesNotExist”错误。

以下是它如何运作的骨架:

  • 有人下了订单,其详细信息会保存在名为“trader_order”的表中的记录中。
  • 该对象中的值用于在另一个表中创建记录(与此处的问题无关,除了他们成功使用新订单的ID之外)。
  • 然后将订单记录的ID推入FIFO缓冲区。
  • 执行所有操作的功能然后发送电子邮件,然后结束。

另一个django脚本正在读取FIFO缓冲区,该脚本正在等待将ID传递给它(在后台作为守护进程运行)。收到该ID后,它会尝试加载具有该ID的订单记录,并对其进行处理。

这一直运作良好(无论如何都在测试中),直到今天的一个实例。我下了一个测试订单(没什么特别之处),并且收到一个错误,说该记录不存在。我很困惑为什么。这是正在观看缓冲区的代码:

def handle(self, *args, **options):
    ###
    # code chopped out for brevity.  Just opening (successfully) the fifo buffer
    ###

    done = 0 
    str = ''
    while not done:
        chr = fifo.read(1);
        if(len(chr)):
            print "read %s" % chr 
            if(chr == ','):
                str = str.strip()
                if(str == 'quit'):
                    done = 1 
                elif(str.isdigit()):
                    print "We have a valid id: %s" % str 
                    self.process_order(str)
                str = ''
            else:
                str += chr 
        else:
            time.sleep(1)

    fifo.close()     

def process_order(self, order_id): 
    try:
        order = models.Order.objects.get(id=order_id)    
        print "Found Order:"
        print order
    except ObjectDoesNotExist:
        print "Order with id %s does not exist"%order_id
        return

    # code continues here, but is not relevant to the question

以下是它在控制台上输出的内容:

read 1
read 2
read 3
read 1
read 6
read 7
read ,
We have a valid id: 123167
Order with id 123167 does not exist

当我查看数据库时,该ID确实存在。我不知道为什么它给了我这个错误。我也无法重现它。当我手动将相同的id传递给缓冲区时,它完美地处理了订单。当我试图重现这种情况时,它又完美地运作了。

这可能是因为这两位代码分别连接到MySQL服务器吗?也许在侦听脚本尝试从数据库中读取记录之前需要刷新某些东西?

这里有几个相关信息:

  • 我在django的manage.py(“./manage.py runserver 0.0.0.0:8000”)
  • 的测试环境中运行该页面
  • 上面的代码也作为后台任务运行manage.py(“./ manage.py cronprocessorders”)
  • 数据库在MySQL中
  • 在Ubuntu发行版上运行

更新

根据提出的要求,这里有更多代码。这是实际放置顺序的函数,并将其ID放入上面代码读取的缓冲区中:

def order_place(self, order):
    '''Place and order on the system. The system will deduct the fee, escrow the amount and 
    create an unprocessed open order.
    '''
    balance = self.balance()
    for cur, bal in balance.items():
        limit = self.limit(cur, 'balance')
        if limit != None and bal > limit:
            raise BalanceLimit(limit, cur) 

    if order.order_total() > balance[order.currency_from()]:
        raise NotSufficientFunds

    order.profile = self 

    # Set up the fee for the order
    tr_fee = Transaction()
    tr_fee.profile = order.profile
    tr_fee.reason = 'fee'
    tr_fee.currency = order.currency_from()
    tr_fee.amount = -order.fee()
    tr_fee.notes = "%.2f%%" % (order.feerate())

    order.save()

    # Commit the fee now that the order is saved
    if tr_fee.amount < 0: 
        tr_fee.processed = datetime.datetime.now()
        tr_fee.order = order
        tr_fee.save()

    if order.remaining > 0: 
        # Put the remaining into escrow (debit)
        tr_da = Transaction()
        tr_da.profile = order.profile
        tr_da.processed = datetime.datetime.now()
        tr_da.reason = 'escrow'
        tr_da.order = order
        tr_da.currency = order.currency_from()
        tr_da.amount = -order.escrow()
        tr_da.save()   

    #write the order id to the FIFO process for order filling
    try: 
        fifo = open(settings.FIFO_PROCESS_ORDER_FILE_PATH, 'w+') 
        fifo.write('%s,' % order.id)
        fifo.close()
    except IOError:
        print "file doesn't exist"     

就是这样。回想起来,我在回忆中看到了错误的功能(对不起)。唯一的区别是最后发送的电子邮件。这个没有这样做。传入的“订单”对象是已经擦除的表单数据。

哦,我为craptastic变量名称道歉。我没有写这个。

1 个答案:

答案 0 :(得分:0)

当你说你无法重现它时,它会让我认为我们正在处理竞争条件。也许您发送了该对象以进行创建,然后尝试在创建尚未完成时读取它。它是在黑暗中刺伤,但没有更多的代码,如@krelagin所说,很难得到更好的想法发生了什么。

副手我看不到任何故障,但我不是django内部专家。我建议您查看iconfinder在保存后ObjectNotExist的体验this video。整个视频值得一看,但链接将带您到相关部分。

相关问题