UnboundLocalError: local variable 'prod_Available' referenced before assignment

十年热恋 提交于 2019-12-13 17:18:32

问题


I am developing a reservation system, and i have a function that save the quantity of a product... My question is why I got this problem ? when i

`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

but when i test in the python shell, it works fine :

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

here is my code in 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

and my 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    

can anyone can explain my situation and give some idea on how to solve it...? thanks


回答1:


Sometimes you loop is not entered, so prod_Available is not created, but you try to reference it.

Before the loop put 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



回答2:


Just initialize prod_Available to Zero before the following for statement

for x in range(start_date,end_date + 1): 

It so happens that because you are assigning value to prod_Available inside the loop, there is a possibility that the variable is never assigned and the following if statement would fail.

if prod_Available <= 0:

Instead, doing

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

would resolve your issue




回答3:


You are getting different behaviours due to passing in different values.

For the first call, you are passing check_in='2011-12-15' and check_out='2011-12-10' and for the second, you have checkin='2011-12-10', and checkout='2011-12-15'. I.e, the check in and check out values are swapped.

This means that the for x in range(start_date,end_date + 1): loop will never get executed, thus never setting prod_Available.

There are two obvious fixes here:

  1. Improve parameter validation, and report an error if the check out date is before the check in date.

  2. Set prod_Available to zero before you start the loop. This will ensure that it is always set, even if the loop does not execute.



来源:https://stackoverflow.com/questions/8429407/unboundlocalerror-local-variable-prod-available-referenced-before-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!