UnboundLocalError:在赋值之前引用了局部变量“response”

2024-03-29 07:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

从同一个程序得到随机结果

我正在使用python请求库进行post调用。我的程序有时运行得很好,但有时会出现错误“UnboundLocalError:localvariable'response'referenced before assignment”。你知道吗

def test_fun():
    try:
        response = requests.get(f"{Base_URI}/Calls.json", auth=(AccSid, AccToken))
    except Exception as err:
        print(f'Other error occurred: {err}')

    assert response.status_code == 200

"UnboundLocalError: local variable 'response' referenced before assignment"

Tags: test程序responsedef错误postrequestserr
2条回答

就像Green斗篷人说的,当异常发生时,response变量是未定义的。这会导致错误。要解决此问题,可以将else语句添加到try

def test_fun():
    try:
        response = requests.get(f"{Base_URI}/Calls.json", auth=(AccSid, AccToken))
    except Exception as err:
        print(f'Other error occurred: {err}')
    else:
        assert response.status_code == 200

else块在没有引发异常时运行。请注意,这与finally不同,后者总是运行,而不管是否引发了错误。你知道吗

如果请求未成功,可以使用raise_for_status()引发异常。你知道吗

try:
    response = requests.get(url)

    # raise exception only if the request was unsuccessful
    response.raise_for_status()
except HTTPError as err:
    print(err)
else:
    # check the exact status and do your stuff.

相关问题 更多 >