一切都在几个小时内完美无缺,然后我会收到这个错误,它会停止运行。
todolist_items = len(todoalso)
UnboundLocalError: local variable 'todoalso' referenced before assignment
我认为这是我遇到麻烦的部分,但我不明白为什么。
response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
if response.status_code == 200:
todoalso = response.json()
global todolist_items
todolist_items = len(todoalso)
答案 0 :(得分:1)
您需要捕获响应失败的情况,并记录它以查看原因。
if response.status_code == 200:
todoalso = response.json()
else:
todoalso = None
print response.status_code,response
答案 1 :(得分:0)
我会比其他人更进一步并建议:
response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
global todolist_items
if response.status_code == 200:
todoalso = response.json()
# Let's assign this variable here, where we know that the status code is 200
todolist_items = len(todoalso)
else:
# instead of simply assigning the value "None" to todoalso, let's return the response code if it's not 200, because an error probably occurred
print response.status_code
答案 2 :(得分:-1)
在这种情况下,我认为响应代码不是200,所以直接转到
todolist_items = len(todoalso)
没有if分支中的赋值。 也许最好将其修改为
response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
if response.status_code == 200:
todoalso = response.json()
global todolist_items
todolist_items = len(todoalso)
根据@ResetACK的建议,我添加了一点改动
response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
if response.status_code == 200:
todoalso = response.json()
global todolist_items
todolist_items = len(todoalso)
else:
requests.raise_for_status()