Jump to content

Python Requests: Error when inside Try, inside if

LewisSpring
Go to solution Solved by LewisSpring,
2 minutes ago, WereCatf said:

Declare the mail - variable before the if - clauses. Even just a mail = None would suffice as a declaration and should fix the issue.

Hi there! .

I just realised the issue - It's trying to act on something that hasn't been set - since email was 0, it was not creating the "variable" to get the text from.

 

Thanks!

Hi there,

 

I have a script that attempts to post a request, but is set up to catch exeptions.

 

    try:
        mail = requests.post(mailurl, data=data)
    except requests.exceptions.RequestException:
        writelogevent("Error making mail request!",1)

This works fine.

 

Where these do not:

if email == 1:
    try:
        mail = requests.post(mailurl, data=data)
    except requests.exceptions.RequestException:
        writelogevent("Error making mail request!",1)
_____________________________________________________________
try:
    if email == 1:
        mail = requests.post(mailurl, data=data)
except requests.exceptions.RequestException:
    writelogevent("Error making mail request!",1)

and generate this error:

  File "TEST.py", line 118, in request
    writelogevent(mail.text,0)
NameError: name 'mail' is not defined

when trying to use "mail.text"  outside of the IF/TRY. This works fine for a request that is only in a try loop, with near identical code.

I've tried making the "mail" variable global from inside the function

 

Thanks!

UTC/GMT (Except during BST)

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, TheLewisS1 said:

when trying to use "mail.text"  outside of the IF/TRY. This works fine for a request that is only in a try loop, with near identical code.

Declare the mail - variable before the if - clauses. Even just a mail = None would suffice as a declaration and should fix the issue.

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, WereCatf said:

Declare the mail - variable before the if - clauses. Even just a mail = None would suffice as a declaration and should fix the issue.

Hi there! .

I just realised the issue - It's trying to act on something that hasn't been set - since email was 0, it was not creating the "variable" to get the text from.

 

Thanks!

UTC/GMT (Except during BST)

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×