从同一程序中获取随机结果
我正在使用python请求库进行后期调用。我的程序有时可以按预期工作,但有时会出现错误“ UnboundLocalError:分配前引用了本地变量'response'”。
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"
答案 0 :(得分:0)
就像Green Cloak Guy所说的那样,当发生异常时,您的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
,后者始终运行无论是否引发错误。
答案 1 :(得分:0)
如果请求失败,则可以使用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.