UnboundLocalError:赋值前引用的局部变量'prod_Available'

时间:2011-12-08 10:21:06

标签: python django django-piston

我正在开发一个预订系统,我有一个节省产品数量的功能......我的问题是为什么我遇到这个问题?当我

`curl -l -X POST -d "product=3&client=1&function=insert_booking&check_in=2011-12-15&check_out=2011-12-10&no_of_adult=2&no_of_kid=1&quantity=2&first_name=asda&last_name=sdsd&contact=34343" http://127.0.0.1:8000/api/reserve`


Piston/0.3dev (Django 1.3.1) crash report:

Traceback (most recent call last):

  File "/home/agileone/workspace/bookproj/api/handlers.py", line 206, in create
    prodAvailable = Hotel.objects.get_hotel_sum_quantity(attrs['product'], attrs['check_in'], attrs['check_out'])

  File "/home/agileone/workspace/bookproj/../bookproj/booking/models.py", line 49, in get_hotel_sum_quantity
    if prod_Available <= 0:

UnboundLocalError: local variable 'prod_Available' referenced before assignment

但是当我在python shell中测试时,它运行正常:

>>> from booking.models import *
>>> Hotel.objects.get_hotel_sum_quantity(3, '2011-12-10', '2011-12-15')1

这是我在models.py中的代码

def get_hotel_sum_quantity(self, product_id, checkin_date, checkout_date):
        check_in = datetime.datetime.strptime(checkin_date, '%Y-%m-%d')
        check_in = check_in.date()
        start_date = check_in.day

        check_out = datetime.datetime.strptime(checkout_date, '%Y-%m-%d')
        check_out = check_out.date()
        end_date = check_out.day

        prod = Product.objects.get(id=product_id)

        for x in range(start_date,end_date + 1):
            x = x - start_date
            delta = datetime.timedelta(days=x)
            all_date = check_in + delta
            sumOfQuantity = HotelCheck.objects.filter(date_booked=all_date, product=prod).aggregate(Sum('quantity'))['quantity__sum']
            if sumOfQuantity == None:
                sumOfQuantity = 0
            prod_Available = prod.quantity - sumOfQuantity
            #global prod_Available
        if prod_Available <= 0:
            status = 0
        else:
            status = 1

        return status

和我的handlers.py

if attrs['function'] == 'insert_booking':

                prodAvailable = Hotel.objects.get_hotel_sum_quantity(attrs['product'], attrs['check_in'], attrs['check_out'])
                if float(prodAvailable) <= 0:
                    disp = Hotel.objects.get_hotel_show_available(attrs['product'], attrs['check_in'], attrs['check_out'])
                    return {'status': '0', 'message': 'not OK!'}, disp    

任何人都可以解释我的情况,并就如何解决它提出一些想法......? 感谢

3 个答案:

答案 0 :(得分:1)

有时您未输入循环,因此未创建prod_Available,但您尝试引用它。

在循环之前放prod_Available = 0

    prod = Product.objects.get(id=product_id)

    prod_Available = 0 # !

    for x in range(start_date,end_date + 1):
        x = x - start_date
        delta = datetime.timedelta(days=x)
        all_date = check_in + delta
        sumOfQuantity = HotelCheck.objects.filter(date_booked=all_date, product=prod).aggregate(Sum('quantity'))['quantity__sum']
        if sumOfQuantity == None:
            sumOfQuantity = 0
        prod_Available = prod.quantity - sumOfQuantity
        #global prod_Available
    if prod_Available <= 0:
        status = 0
    else:
        status = 1

    return status

答案 1 :(得分:1)

只需在以下语句

之前将prod_Available初始化为Zero
for x in range(start_date,end_date + 1): 

碰巧因为你在循环中为prod_Available赋值,所以有可能永远不会分配变量而后面的if语句会失败。

if prod_Available <= 0:

相反,做

prod_Available =0  #Initialize outside loop
for x in range(start_date,end_date + 1): 

将解决您的问题

答案 2 :(得分:1)

由于传递了不同的值,您获得了不同的行为。

对于第一个电话,您正在传递check_in='2011-12-15'check_out='2011-12-10',而第二个电话则是checkin='2011-12-10'checkout='2011-12-15'。即,交换签入和签出值。

这意味着永远不会执行for x in range(start_date,end_date + 1):循环,因此永远不会设置prod_Available

这里有两个明显的修复:

  1. 改进参数验证,如果签出日期早于签入日期,则报告错误。

  2. 在开始循环之前将prod_Available设置为零。这将确保始终设置它,即使循环不执行。