URL: /plog/whitelist-blacklist-logic/whiteblack_list_example.py

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?

Comments

Post your own comment
djo

Suggestion: this is a function for white/blacklisting strings - there's nothing email address-specific in here. I'd rename it to match the more general case.

Peter Bengtsson

Very good point. I was too simpleminded at that late hour. The function is extracted from a class which deals with email addresses and stuff so over there it made sense.

Sylvain Hellegouarch

Interesting but then it depends on you email adresses are entered to your system.

If one can enter whatever adress, what's the point? :)

I could have put bill.gates@microsoft.com into this comment email adress. How could you have prevented me from it?

Peter Bengtsson

The point? If you don't like the default behaviour set the default_accept parameter to False or look at my second example in the .py file.

djo

Peter - if you set default_accept to FALSE, do you need the blacklist at all any more?

Peter Bengtsson

Again a very good point. No, if you set default_accept to false, then the blacklist is useless.

Mohamed

may you Assist me Please

Your email will never ever be published.

Related posts