我试图通过一个循环来向MySQL数据库添加一些数据,该循环遍历返回JSON文件的API。我正在使用Python和MySQLdb模块。
出于某种原因,我得到了臭名昭着的UnboundLocalError。我查看了这个问题发生时的其他情况,并且已经在StackOverflow上得到了解答,但没有任何共鸣,我无法直接应用于此问题。
这是我的代码:
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
答案 0 :(得分:2)
问题是item
仅在您输入for
循环
for item in data['items']:
...
如果data['items']
为空,则您永远不会这样做,item
仍然未分配。
答案 1 :(得分:1)
由于这个脚本遍历循环并且一些返回的变量是NULL python然后(理所当然地)抛出UnboundLocalError,因为变量不存在/尚未声明。
我尝试使用以下方法处理此问题:
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