赋值前引用的局部变量 'sql'

local variable 'sql' referenced before assignment

您好,我正在尝试使用 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':有自己的函数来执行,我希望其他条件跳转到代码末尾的最后一个游标函数。

问题

local variable 'sql' referenced before assignment 表示当您尝试将它与 cursor.execute(sql) 一起使用时 sql 尚未分配。

当您的 if/elif 检查中 params["type"] == 'product' 或 none 为真时就是这种情况。比如if params["type"]就是foosql不会被赋值。

解决方案

params["type"] == 'product'

时给sql赋值

使用 else 语句为 sql 赋值,或者在 params["type"] 是预期字符串的 none 时引发错误。

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

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)

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

您应该重新安排 if 序列以忽略 sql 为空的情况。否则你可以在上面添加 sql = 'some default value',但它已经很难阅读了。

你可以在开始时给sql一个默认值:

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

我改了之后

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

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

它起作用是因为 get_product_report 是它自己的函数,所以没有任何 return 结果到 param = 'product' 条件,所以它在产品参数行中是错误的(return None)