分配前引用的本地变量“ sql”

时间:2019-03-19 10:58:50

标签: python sql django indentation

您好,我尝试使用if / elif编写函数,但是在elif之后尝试执行最终的游标函数时遇到了麻烦。我认为我的缩进是错误的,并且我现在已经试图在一天之内找出错误所在:

def api_report(request):
    params = request.GET
    if params["type"] == 'revenue':
        sql = get_revenue_query(params)

    elif params["type"] == 'order_count':
        sql = get_order_created_count(params)

    elif params["type"] == 'product_count':
        sql = get_product_count(params)

    elif params["type"] == 'order_card_created_count':
        sql = get_order_card_created_count(params)

    elif params["type"] == 'product_count':
        sql = get_product_count(params)

    elif params["type"] == 'card':
        sql = get_card_query(params)

    elif params["type"] == 'order_not_card_created_count':
        sql = get_order_not_card_created_count(params)

    elif params["type"] == 'product':
        get_product_report(params)

    elif params["type"] == 'order_rate_by_district':
        sql = get_order_rate_by_district(params)

        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()
            data = []
            for row in rows:
                data.append(OrderRateDataEntry(row[0], row[1], row[2]))
        serializer = OrderRateDataEntrySerializer(data, many=True)
        return JsonResponse(serializer.data, safe=False)

    with connection.cursor() as cursor:
        cursor.execute(sql)
        rows = cursor.fetchall()
        data = []
        for row in rows:
            data.append(TimeSeriesDataEntry(row[0], row[1]))
    serializer = TimeSeriesDataEntrySerializer(data, many=True)
    return JsonResponse(serializer.data, safe=False)

错误:

cursor.execute(sql)  UnboundLocalError: 
    local variable 'sql' referenced before assignment

elif params["type"] == 'product':elif params["type"] == 'order_rate_by_district':拥有自己要执行的函数,我希望其他条件跳转到代码末尾的最后一个光标函数。

5 个答案:

答案 0 :(得分:1)

一旦运行程序,这就是我假设发生的情况(读#)

def api_report(request):
    params = request.GET
    if params["type"] == 'revenue': # False so sql is not made, move to next elif
        sql = get_revenue_query(params)

    elif params["type"] == 'order_count': # False so sql is not made, move to next elif
        sql = get_order_created_count(params)

    elif params["type"] == 'product_count': # False so sql is not made, move to next elif
        sql = get_product_count(params)

    elif params["type"] == 'order_card_created_count': # False so sql is not made, move to next elif
        sql = get_order_card_created_count(params)

    elif params["type"] == 'product_count': # False so sql is not made, move to next elif
        sql = get_product_count(params)

    elif params["type"] == 'card': # False so sql is not made, move to next elif
        sql = get_card_query(params)

    elif params["type"] == 'order_not_card_created_count': # False so sql is not made, move to next elif
        sql = get_order_not_card_created_count(params)

    elif params["type"] == 'product': # False so sql is not made, move to next elif
        get_product_report(request) # P.S There is also a chance that if this is run then sql variable will also not be made!

    elif params["type"] == 'order_rate_by_district':  # This is also false so code leaves.
        sql = get_order_rate_by_district(params)

        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()
            data = []
            for row in rows:
                data.append(OrderRateDataEntry(row[0], row[1], row[2]))
        serializer = OrderRateDataEntrySerializer(data, many=True)
        return JsonResponse(serializer.data, safe=False)

        pass
    # When the code is here it still didn't made variable sql. Thus so will crashes when refere to variable sql as it wasn't yet created
    with connection.cursor() as cursor:
        cursor.execute(sql) # sql was never made here and thus doesn't exist. Code crashes here.
        rows = cursor.fetchall()
        data = []
        for row in rows:
            data.append(TimeSeriesDataEntry(row[0], row[1]))
    serializer = TimeSeriesDataEntrySerializer(data, many=True)
    return JsonResponse(serializer.data, safe=False)

第一个if语句make和空sql变量之前的Maby。 (或您喜欢的默认值)

答案 1 :(得分:0)

问题

local variable 'sql' referenced before assignment意味着当您尝试将sqlcursor.execute(sql)一起使用时,尚未分配params["type"] == 'product'

if params["type"]或您的if / elif检查都不为真时就是这种情况。例如,foosql,将不会分配params["type"] == 'product'

解决方案

else

时为sql分配一个值

使用params["type"]语句为sql分配值或在 ranges: [1.3,1.9,2.05,inf,1.64] 都不是您期望的字符串时引发错误。

答案 2 :(得分:0)

您应该重新排列if序列,以忽略sql为空时的情况。否则,您可以仅在其顶部添加sql = 'some default value',但已经很难阅读。

答案 3 :(得分:0)

您可以在开始时为sql提供默认值:

def api_report(request):
    params = request.GET
    sql=''

答案 4 :(得分:0)

我更改了

 elif params["type"] == 'product':
      get_product_report(request)

 elif params["type"] == 'product': 
      return get_product_report(params)

之所以起作用,是因为get_product_report是它自己的函数,因此没有返回任何返回param ='product'条件的结果,因此从product param行(返回None)是错误的