赋值前引用的MySQLdb错误局部变量(与平常不同)

MySQLdb error local variable referenced before assignment (different than usual)

我正在尝试通过一个循环将一些数据添加到 MySQL 数据库,该循环遍历 API 那个 returns 一个 JSON 文件。我正在使用 Python 和 MySQLdb 模块。

出于某种原因,我遇到了臭名昭著的 UnboundLocalError。当这个问题发生时,我查看了其他场景,并且已经在 Whosebug 上得到了解答,但没有引起我的共鸣,我无法将它直接应用于这个问题。

这是我的代码:

def request(API_KEY, URL, ch_no):
    url = URL + ch_no + '/request'
    request = requests.get(url, auth=(API_KEY, ''))
    data_dict = request.json()
    data_dict_json_dumps = json.dumps(data_dict)
    data = json.loads(data_dict_json_dumps) 

    try:
        for item in data['items']:
            return (item['tag'], item['created_on'], item['delivered_on'], item['satisfied_on'], item['status'], item['particulars']['description'], item['persons_entitled'][0]['name'])   
    except KeyError:
        pass

    try:
        description = item['particulars']['description']
    except KeyError:
        description = None
    try:
        persons_entitled = item['persons_entitled'][0]['name']
    except KeyError:
        persons_entitled = None 

    try:
        cursor.execute("""INSERT INTO companies_and_charges_tmp (tags, company_id, created, delivered, satisfied, status, description, persons_entitled) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", (item.get('tag'), ch_no, item.get('created_on'), item.get('delivered_on'), item.get('satisfied_on'), item.get('status'), description, persons_entitled))
    db.commit()

    finally: 
        time.sleep(0.5)

    del data

for ch_no in ch_nos:
    charges_request(API_KEY, URL, ch_no)

这是完整的错误:

Traceback (most recent call last):
  File "test2.py", line 58, in <module>
    charges_request(API_KEY, URL, ch_no)
  File "test2.py", line 49, in charges_request
    cursor.execute("""INSERT INTO companies_and_charges_tmp (etags, company_id, created, delivered, satisfied, status, description, persons_entitled) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", (item.get('etag'), ch_no, item.get('created_on'), item.get('delivered_on'), item.get('satisfied_on'), item.get('status'), description, persons_entitled))
UnboundLocalError: local variable 'item' referenced before assignment

因为这个脚本遍历循环并且一些返回的变量是 NULL python 然后(理所当然地)抛出 UnboundLocalError 因为变量没有 there/hasn 没有被声明。

我试图通过以下方式处理这个问题:

except KeyError:

但是,我们这里处理的错误不仅仅是KeyErrors,还有UnboundLocalErrors,所以只处理其中一个错误是没有效果的。

我按以下方式修改了脚本(请注意,这适用于 Python 2.7 我不确定在 Python 3 中是否可以使用相同的语法):

try:
    description = item['particulars']['description']
except (UnboundLocalError, KeyError):
    #declaring the description as None if not there so MySQL/Python don't throw an error
    description = None

然后在将数据添加到 MySQL 数据库时,我还使用了错误处理程序并传递了一个:

try:
    cursor.execute("""INSERT INTO companies_and_charges_tmp (etags, company_id, created, delivered, satisfied, status, description, persons_entitled) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", (item.get('etag'), ch_no, item.get('created_on'), item.get('delivered_on'), item.get('satisfied_on'), item.get('status'), description, persons_entitled))
    db.commit()
except UnboundLocalError:
     pass

问题是 item 仅在您进入 for 循环时分配

for item in data['items']:
    ...

如果 data['items'] 为空,则永远不会这样做,并且 item 保持未分配状态。