pyinotify code cleanup smtplib

232 views Asked by At

New Coder here

I'm hoping to be able to clean this code up a bit. I want to be able to move the smtplib stuff out of the class but I still need it to send an email with the pinotify data If you look at my code you'll see. It is very redundant.

if notify data > send email with file created data

if notify data > send email with file deleted data

How can I consolidate this.

import os, pyinotify, time, smtplib, string
from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent


wm = WatchManager()
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE  # Watched Events

class PTmp(ProcessEvent):
  def process_IN_CREATE(self,event):
    output = "Created: %s " % os.path.join(event.path, event.name) 
    localtime = time.asctime( time.localtime(time.time()) )
    final = output + localtime
    SUBJECT = "Directory Changed"
    TO = "user@localhost"
    FROM = "[email protected]"
    text = final
    BODY = string.join((
            "From: %s" % FROM,
            "To: %s" % TO,
            "Subject: %s" % SUBJECT ,
            "",
            text
            ), "\r\n")  
    s=smtplib.SMTP('localhost')
    s.sendmail(FROM, TO, BODY)
    s.quit()
  def process_IN_DELETE(self,event):
    output = "Removed: %s" % os.path.join(event.path, event.name)
    localtime = time.asctime( time.localtime(time.time()) )
    final = output + localtime
    SUBJECT = "Directory Changed"
    TO = "user@localhost"
    FROM = "[email protected]"
    text = final
    BODY = string.join((
            "From: %s" % FROM,
            "To: %s" % TO,
            "Subject: %s" % SUBJECT ,
            "",
            text
            ), "\r\n")
    s=smtplib.SMTP('localhost')
    s.sendmail(FROM, TO, BODY)
    s.quit()

notifier=Notifier(wm, PTmp())
wdd=wm.add_watch('/var/test',mask,rec=True)

while True:  # Loop Forever
  try:
     # process the queue of events as explained above
     notifier.process_events()
     if notifier.check_events():
        # read notified events and enqeue them
        notifier.read_events() 

  except KeyboardInterupt:
     # Destroy the inotify's instance on this interupt(stop monitoring)
     notiifier.stop()
     break
1

There are 1 answers

0
Denis On BEST ANSWER

If you want to make your code better the first thing what could do is place all your constants in separate file, like myapp.conf:

 SUBJECT = {'dc':'Directory changed', 'sf':'Server fault' and etc}
 TO = 'user@localhost'
 FROM = 'user@localhost'
 and etc ...

for forming mail body you could use templates engines like Mako and with it you can place mail template to another separate file. And you could separate your class implement from main code. After that you code will stay more flexible and it will be easier to maintain.