Whitelist blacklist logic
02 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', 'firstname.lastname@example.org') 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?