2

Getting random results from same program

I am making a post call using python requests library. My program works fine sometimes as I expected but gives error "UnboundLocalError: local variable 'response' referenced before assignment" some other times.

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"
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • 1
    `response` doesn't get set if an exception occurs. In which case you print the "other error occurred" message and then continue normally out of the `except` block. Since the `response = ...` statement didn't execute fully, `response` doesn't exist, so when you try to reference it in the `assert` statement, you get an error. – Green Cloak Guy Nov 12 '19 at 01:28
  • Does this answer your question? [UnboundLocalError: local variable referenced before assignment when reading from file](https://stackoverflow.com/questions/15367760/unboundlocalerror-local-variable-referenced-before-assignment-when-reading-from) – CristiFati Nov 12 '19 at 01:28
  • I really appreciate your answer but in case of exception it does not print anything that I have given in the except block. any suggestion would be appreciated. – Kanchan Mittal Nov 12 '19 at 01:48

2 Answers2

2

Like Green Cloak Guy said, when an exception occurs, your response variable is undefined. This causes the error. To fix this, you can add an else statement to your 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

The else block is ran when there were no exceptions raised. Note that this is different from finally, which always runs regardless of whether an error was raised or not.

adrianp
  • 999
  • 1
  • 8
  • 13
0

You can use raise_for_status() to raise an exception if the request wasn't successful.

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.
Rohit
  • 3,659
  • 3
  • 35
  • 57
  • Pls consider accepting or upvoting the answer so that it is clear for others that your issue is resolved. – Rohit Nov 17 '19 at 04:26