【问题标题】:local variable referenced before assignment json赋值 json 之前引用的局部变量
【发布时间】:2018-05-28 06:49:37
【问题描述】:

在几个小时内一切正常,然后我会收到这个错误,它会停止运行。

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)

【问题讨论】:

标签: python json


【解决方案1】:

您需要捕获响应失败的情况,并将其记录下来以查看原因。

if response.status_code == 200:
    todoalso = response.json()
else:
    todoalso = None
    print response.status_code,response

【讨论】:

  • 这将修复 OP 描述的错误,但这意味着他们永远不会发现实际问题是什么
  • 谢谢,添加了打印语句以找出实际问题。其余的调试由 OP 自行决定。
【解决方案2】:

我会比其他人更进一步并建议:

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

【讨论】:

    【解决方案3】:

    这种情况下我会认为响应码不是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()
    

    【讨论】:

    • 这将阻止 OP 描述的错误发生,但它会暴露其他问题,例如,如果 response.status_code 不等于 200 会发生什么?
    • @ResetACK,感谢您的建议。我修改了答案
    猜你喜欢
    • 2015-04-22
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2013-08-02
    • 2011-11-06
    • 2018-01-12
    相关资源
    最近更新 更多