Postgres where Except sends an email.

This is the place for queries that don't fit in any of the other categories.

Postgres where Except sends an email.

Postby def(PitoneMaledetto) » Thu May 08, 2014 3:59 pm

Hi all,
this is my first attempt in Python :)
What I am trying to do is:
1) Check the connection to my Postgres DB
2) If connection attempts fail 3 times
3) Except by sending an email

The email bit alone works fine but when I try to call the function in except (no matter what I call) it does not work.
Can someone please shed a light on me?
Thanks for your time.
Pitone Maledetto

Code: Select all
 #!usr/bin/python
  2 import psycopg2
  3 import sys
  4 import smtplib
  5 from email.mime.text import MIMEText
  6
  7 #The connection bit
  8 conn = None
  9 attempts = 0
 10
 11 while attempts < 3:
 12         try:
 13                 conn = psycopg2.connect("host='myhost' dbname='myDB' user='myuser' password='lmypassword'");
 14
 15         except  psycopg2.DatabaseError, e:
 16                 attempts += 1
 17                 send_email(msg)
 18
 19         finally:
 20                 if conn:
 21                         conn.close()
 22
 23 #The email bit
 24
 25 EMAIL_SUBJECT = "DB Connection Failed!"
 26 EMAIL_FROM = "myemail@mydomain.com"
 27 EMAIL_RECEIVERS = ['myemail@mydomain.com']
 28
 29 def listToStr(lst):
 30         """This method makes comma separated list item string"""
 31         return ','.join(lst)
 32
 33 def send_email(msg):
 34         """This method sends an email"""
 35
 36         msg_header = "From: " + EMAIL_FROM + "\n" + \
 37                         "To: " + listToStr(EMAIL_RECEIVERS) + "\n" + \
 38                         "Subject: " + EMAIL_SUBJECT + "\n"
 39         msg_body = msg_header + msg
 40
 41         try:
 42                 #establish a connection with the remote SMTP server.
 43                 smtpObj = smtplib.SMTP('mySMTPserver')
 44                 #now send the email.
 45                 smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
 46                 #close the connection and session.
 47                 smtpObj.quit()
 48         except SMTPException as error:
 49                 print "Error: unable to send email : {err}".format(err=error)
 50 def main():
 51         send_email("I have tried to connect to the Database but I can't! Your attention is required. Thank you.");
 52
 53 if __name__ == "__main__":
 54         main()
Last edited by Yoriz on Thu May 08, 2014 4:37 pm, edited 1 time in total.
Reason: First post lock
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm

Re: Postgres where Except sends an email.

Postby Yoriz » Thu May 08, 2014 4:43 pm

Hi welcome to the forum.
Please read the new user read this link in my signature.

You have not stated in what way it does not work.

At first glance it looks like when you are calling send_email(msg) in your exception you have not set a value to msg.
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 831
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Postgres where Except sends an email.

Postby lorddarthvader » Thu May 08, 2014 5:07 pm

-nvm i'm wrong, was too lazy to go through your entire code-
Last edited by lorddarthvader on Fri May 09, 2014 2:28 am, edited 1 time in total.
--If at first you don't succeed, destroy all evidence that you tried.
My github
fite me
User avatar
lorddarthvader
 
Posts: 33
Joined: Mon Apr 07, 2014 11:38 am

Re: Postgres where Except sends an email.

Postby def(PitoneMaledetto) » Thu May 08, 2014 7:26 pm

Yoriz wrote:Hi welcome to the forum.
At first glance it looks like when you are calling send_email(msg) in your exception you have not set a value to msg.


This is what I get:
Code: Select all
Traceback (most recent call last):
  File "script.py", line 17, in <module>
    send_email(msg)
NameError: name 'send_email' is not defined


but I was under the impression that I have stated the value here:
Code: Select all
def send_email(msg):
          """This method sends an email"""
 
          msg_header = "From: " + EMAIL_FROM + "\n" + \
                          "To: " + listToStr(EMAIL_RECEIVERS) + "\n" + \
                          "Subject: " + EMAIL_SUBJECT + "\n"
          msg_body = msg_header + msg
 
          try:
                  #establish a connection with the remote SMTP server.
                  smtpObj = smtplib.SMTP('mySMTPserver')
                  #now send the email.
                  smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
                  #close the connection and session.
                  smtpObj.quit()
          except SMTPException as error:
                  print "Error: unable to send email : {err}".format(err=error)
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm

Re: Postgres where Except sends an email.

Postby def(PitoneMaledetto) » Thu May 08, 2014 7:30 pm

lorddarthvader wrote:try and except is for exception handling and in this case you should you conditional statements


something like this?

if (true)
do nothing
else
send the email
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm

Re: Postgres where Except sends an email.

Postby stranac » Thu May 08, 2014 7:31 pm

The call to the function is above the function definition.
The function is not yet defined when you try calling it.

Also, don't post line numbers with your code.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1143
Joined: Thu Feb 07, 2013 3:42 pm

Re: Postgres where Except sends an email.

Postby def(PitoneMaledetto) » Thu May 08, 2014 7:38 pm

stranac wrote:The call to the function is above the function definition.
The function is not yet defined when you try calling it.

Also, don't post line numbers with your code.


Sorry for the line numbers, that was my very first post and then I read the rules. I will try my best.
That make sense, I will try by putting the #Email bit before the #Connection bit.

If I do that do I need to delete this?:
Code: Select all
 if __name__ == "__main__":
         main()
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm

Re: Postgres where Except sends an email.

Postby stranac » Thu May 08, 2014 7:40 pm

def(PitoneMaledetto) wrote:If I do that do I need to delete this?:

No.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1143
Joined: Thu Feb 07, 2013 3:42 pm

Re: Postgres where Except sends an email.

Postby def(PitoneMaledetto) » Thu May 08, 2014 7:44 pm

My code without line numbers (indent should be fine):

Code: Select all
#!usr/bin/python
import psycopg2
import sys
import smtplib
from email.mime.text import MIMEText

#The connection bit
conn = None
attempts = 0

while attempts < 3:
        try:
                 conn = psycopg2.connect("host='myhost' dbname='myDB' user='myuser' password='lmypassword'");

        except  psycopg2.DatabaseError, e:
                attempts += 1
                send_email(msg)

        finally:
                 if conn:
                         conn.close()

#The email bit

EMAIL_SUBJECT = "DB Connection Failed!"
EMAIL_FROM = "myemail@mydomain.com"
EMAIL_RECEIVERS = ['myemail@mydomain.com']

def listToStr(lst):
         """This method makes comma separated list item string"""
         return ','.join(lst)

def send_email(msg):
         """This method sends an email"""

         msg_header = "From: " + EMAIL_FROM + "\n" + \
                         "To: " + listToStr(EMAIL_RECEIVERS) + "\n" + \
                         "Subject: " + EMAIL_SUBJECT + "\n"
         msg_body = msg_header + msg

         try:
                 #establish a connection with the remote SMTP server.
                 smtpObj = smtplib.SMTP('mySMTPserver')
                 #now send the email.
                 smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
                 #close the connection and session.
                 smtpObj.quit()
         except SMTPException as error:
                 print "Error: unable to send email : {err}".format(err=error)
 def main():
         send_email("I have tried to connect to the Database but I can't! Your attention is required. Thank you.");
 
 if __name__ == "__main__":
          main()
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm

Re: Postgres where Except sends an email.

Postby def(PitoneMaledetto) » Thu May 08, 2014 7:59 pm

Right now I have this:

Code: Select all
#!usr/bin/python
import psycopg2
import sys
import smtplib
from email.mime.text import MIMEText

#The email bit
EMAIL_SUBJECT = "DB Connection Failed!"
EMAIL_FROM = "myemail@mydomain.com"
EMAIL_RECEIVERS = ['myemail@mydomain.com']
def listToStr(lst):
         """This method makes comma separated list item string"""
         return ','.join(lst)
def send_email(msg):
         """This method sends an email"""
          msg_header = "From: " + EMAIL_FROM + "\n" + \
                         "To: " + listToStr(EMAIL_RECEIVERS) + "\n" + \
                         "Subject: " + EMAIL_SUBJECT + "\n"
         msg_body = msg_header + msg
          try:
                 #establish a connection with the remote SMTP server.
                 smtpObj = smtplib.SMTP('mySMTPserver')
                 #now send the email.
                 smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
                 #close the connection and session.
                 smtpObj.quit()
         except SMTPException as error:
                 print "Error: unable to send email : {err}".format(err=error)
def main():
         send_email("I have tried to connect to the Database but I can't! Your attention is required. Thank you.");
 
if __name__ == "__main__":
          main()

#The connection bit
conn = None
attempts = 0

while attempts < 3:
        try:
                conn = psycopg2.connect("host='myhost' dbname='myDB' user='myuser' password='lmypassword'");
         except  psycopg2.DatabaseError, e:
                attempts += 1
                send_email(msg)
         finally:
                 if conn:
                         conn.close()


...and:
1) it sends the email even if it should not (the connection is successful)
2) after running: python script.py the pointer does not stop flashing as if the script will run forever hence I don't have my prompt me@debian:-$ back as it does when a script has finished executing.
Last edited by def(PitoneMaledetto) on Thu May 08, 2014 8:21 pm, edited 1 time in total.
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm

Re: Postgres where Except sends an email.

Postby def(PitoneMaledetto) » Thu May 08, 2014 8:05 pm

this is what I get when ctrl+c

^CTraceback (most recent call last):
File "script.py", line 47, in <module>
conn = psycopg2.connect("host='myhost dbname='myDB' user='myuser' password='mypassword'");
File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
KeyboardInterrupt
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm

Re: Postgres where Except sends an email.

Postby def(PitoneMaledetto) » Mon May 12, 2014 8:36 am

think the best way if I split the code and work out the issues that way.
I created a new file with only this in:

Code: Select all
#!usr/bin/python
import psycopg2

conn = None
attempts = 0

while attempts < 3:
        try:
                conn = psycopg2.connect("host='10.101.5.3' dbname='postgres' user='giuseppe' password='letmein'");

                print "Connected!"

#      except  psycopg2.DatabaseError, e:
#                attempts += 1
#                send_email(msg)
         finally:
                 if conn:
                       conn.close()


Having the except commented out I get into an endless loop of:
Connected!
Connected!
Connected!
etc etc

So my first objective is to have Python check the connection and if the connection is achieved have just 1 Connected! printed out. That is to say if the connection is a success stop checking. If instead 3 connection attempts are failed then go and parse the except bit....any ideas?
Thank you
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm

Loop sorted

Postby def(PitoneMaledetto) » Wed May 14, 2014 4:06 pm

I managed to work the loop thought to share:
Code: Select all
#setting up the connection parameters
conn_string = "host='hostname' dbname='dbname' user='myname' password='mypassword' "

#the looping function
def main():
    times = 3
    connected = False
    while(not connected and times > 0):
        try:
            conn = psycopg2.connect(conn_string)
            connected = True
        except psycopg2.OperationalError, e:
            time.sleep(10)
        times -= 1
    if (connected):
        print "Connected!"
    else:
        print "Connection Failed!"
if __name__ == "__main__":
    main()
User avatar
def(PitoneMaledetto)
 
Posts: 9
Joined: Thu May 08, 2014 3:52 pm


Return to General Coding Help

Who is online

Users browsing this forum: boris39 and 3 guests