Whitelist blacklist logic

http://peterbe.mobi/plog/whitelist-b...c/whiteblack_list_example.py

2nd of November 2005

Tonight I need a little function that let me define a list of whitelisted email address and a list of blacklisted email address. This is then "merged" in a function called acceptOriginatorEmail(emailaddress) which is used to see if a particular email address is acceptable.

I've never written something like this before so I had to reinvent the wheel and guess my way towards a solution. My assumptions are that you start with whitelist and return True on a match on the blacklist, then you check against the blacklist and return False on a match and default to True if no match is made.

This makes it possible to define which email addresses should be accepted and which ones should be rejected like this:

 whitelist = ('*@peterbe.com', 'bill.gates@microsoft.com')
 blacklist = ('*@microsoft.com')

Here's the code which does the crucial stuff:

 def acceptOriginatorEmail(self, email, default_accept=True):
     """ return true if this email is either whitelisted or 
     not blacklisted """

     whitelist = self.getWhitelistEmails()
     blacklist = self.getBlacklistEmails()

     # note the order 
     for reject, emaillist in ([False, whitelist], [True, blacklist]):
         for okpattern in emaillist:
             if re.findall(okpattern.replace('*','\S+'), email, re.I):
                 # match!
                 if reject:
                     return False
                 else:
                     return True

     # default is to accept all
     return default_accept

Download whiteblack_list_example.py to see it in action.

What do you think people? Does it make any sense?



Comment

Show all 7 comments
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.